views:

80

answers:

3

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

+6  A: 

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

Joel
A: 

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.

Gianni
Technically, in C++ a boolean is a completely separate type. The compiler silently coerces integers, pointers, etc. to be booleans where required.
Joel
In C++, `bool` is a built-in type, distinct from `int`, usually of different size, with two possible values, `true` and `false`. And, in C++, an `if` statement requires a `bool` as its condition. But there are built-in conversions from integer and pointer types etc. to `bool`.
sbi
I did say 'a fancy way of saying' simply because the complete description was unnecessary for my explanation, but yes, you guys are strictly correct.
Gianni
A: 

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.

JonH
Nit: If it returns any nonzero number, even <0, it would execute.
Joel
Well, but the interesting question is what happens when `select_object` is neither `0` nor `1`.
sbi
@sbi - as I said non-zero will execute.
JonH