为什么“你好”在布尔条件下评估为true? [英] Why does "hello" evaluate as true in a boolean condition?

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

问题描述

我一直在用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();
} 

在此输出是内部如果....我想知道如何这个东西在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 */;

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

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