Haxed
Haxed

Reputation: 2917

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

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

Upvotes: 1

Views: 3087

Answers (3)

JonH
JonH

Reputation: 33163

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.

Upvotes: 0

Gianni
Gianni

Reputation: 4390

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.

Upvotes: 0

Joel
Joel

Reputation: 5674

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

Upvotes: 6

Related Questions