开发者

In C++ syntax, can the condition of the if else, return a int and still execute the statements within

开发者 https://www.devze.com 2023-01-08 12:53 出处:网络
Here is the code which compiles 开发者_运维知识库: int select_object = 0; if( select_object )//condition returns an int

Here is the code which compiles 开发者_运维知识库:

int select_object = 0;

if( select_object )  //condition returns an int
{

     printf("Hello");

}

if condition returns an int and not a boolean will the hello be printed ? When I tested this it printed hello.

Any idea why even for an int it executes the print statement.

THanks


In C and C++, any nonzero integer or pointer is considered true. So, since select_object is 0, it should not be printing Hello.


Boolean logic

1 = True

0 = False

1 && 0 = False 0

1 && 1 = True 1

1 || 1 = True 1

1 || 0 = True 1

So the answer is for non-zero it is considered true, for 0 it is considered false. If your value (your int) returns 0 it won't execute. If it returns a value that is not 0 it will execute.


In C or C++, a bool is just a fancy way of saying 'int with special values'. Every logical test (if, while, for, etc) can use an int or a pointer for its test instead of a bool, and anything that isn't 0 is true. NULLs and 0 are equal in this sense.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号