Are Decimal Values Considered True in C?

Viewed 486

I am currently writing a conditional statement that evaluates floating-point values.

float condition;
if(condition)
  // then do something
else
  // do something else

If condition is, say, 0.5 or 1/2, would the statement be considered True or False? In other words, would the program execute the "then" or the "else" portion?

1 Answers

If the condition is equal to 0, it is considered false, otherwise it is considered true.

Section 6.8.4.1 of the C standard regarding the if statement states:

1 The controlling expression of an if statement shall have scalar type

2 In both forms, the first substatement is executed if the expression compares unequal to 0

Floating point types are considered scalar types, so they are valid as the expression of an if.

This also works for the values infinity and NaN, both of which compare unequal to 0.

Related