0

Is it valid to use an integer variable as a condition?
I mean:

int var = 20;
if (var) {
    //code here
}

I know that when var == 0 it's equivalent to false and true if 1, but otherwise could it be a valid question?

2
Contributors
1
Reply
10
Views
2 Years
Discussion Span
Last Post by deceptikon
1

Is it valid to use an integer variable as a condition?

Yes. This:

if (var)

Is logically synonymous with this:

if (var != 0)

Provided var has an implicit conversion to an integer or boolean type, it's perfectly valid and makes for nice shorthand in some cases. In this case, 0 is false and any non-zero value is true.

Edited by deceptikon

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.