为什么& quot; hello&"在布尔条件下评估为真? [英] Why does "hello" evaluate as true in a boolean condition?

查看:73
本文介绍了为什么& quot; hello&"在布尔条件下评估为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用C语言进行工作,因为这是我刚开始使用的第一语言.这次我用if else语句进行一些编码...我发现了一些我不明白为什么会发生的东西.代码如下

I have been doing work in C language as it was my first language from where i started.This time i was doing some coding with if else statement...and i find something which i cannot understand why it was happening.The code is as follow

#include<stdio.h>
#include<conio.h>

void main()
{
    printf("How If - Else works\n");

    if("hello")
    {
        printf("Inside if\n");
    }
    else
    {
        printf("Inside else\n");
    }

    getch();
} 

在这种情况下,输出为Inside if.....我想知道如何在if语句中对该值求值,并且对我们在if语句中传递的内容没有任何限制.

In this the output was Inside if....i want to know how this thing get evaluated inside the if statement and is there any restriction to what we pass in the if statement.

推荐答案

C确实没有布尔值( true false )(C99确实有)以下说明仍然适用).

C doesn't really have boolean (true or false) values (C99 does, but my notes below still apply).

C解释为 false 的东西是"0";其他一切都是 true ;

What C interprets as false is anything "0"; everything else is true;

如此

if (0) {} else {printf("0 is false\n");}
if (NULL) {} else {printf("NULL is false\n");}
if (0.0) {} else {printf("0.0 is false\n");}

文字字符串被解释为指针...并且它指向实字符,所以它是真的

a literal string is interpreted as a pointer ... and it is pointing to real characters, so it's true

if (1) {printf("1 is true\n");} else {}
if (-1) {printf("-1 is true\n");} else {}
if ("hello") {printf("\"hello\" is true\n");} else {}
if (3.14159) {printf("3.14159 is true\n");} else {}

有趣的是,一个空字符串或字符串"0" 或字符'0' true

Interestingly an empty string or the string "0" or the character '0' is true

if ("") {printf("\"\" is true\n");} else {}
if ("0") {printf("\"0\" is true\n");} else {}
if ('0') {printf("'0' is true\n");} else {}

NUL字符(不是NULL的指针)的 int 值为0,并且为 false

The NUL character (not NULL which is a pointer) has int value 0 and is false

if ('\0') {} else {printf("'\\0' is false\n");}

当您拥有真正的布尔结构时,编译器会发出代码以将其转换为 0 1

What happens when you have a real boolean construct is that the compiler emits code to convert that to 0 or 1

if (a > b) /* whatever */;
// if a is greater than b, the compiler generated code will be something like
if (1) /* whatever */;
// otherwise, if a <= b, the generated code would look like
if (0) /* whatever */;

这篇关于为什么&amp; quot; hello&amp;&quot;在布尔条件下评估为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆