In if (class == 'a','A')
, the left half is the comparison class == 'a'
and may evaluate to either true
or false
(in the boolean sense¹). The right half is just 'A'
, which is not equal to 0
and thus true
. The left half gets evaluated but the result is not used. Then the right half is evaluated, and its "result" is 'A'
, which is true
. Hence, the code acts as if you wrote
if (true)
...
You can check this by using a '0' at the right half:
if (class == 'a', 0)
printf ("if-statement is true\n");
else
printf ("if-statement is false\n");
and running this (after coercing the compiler to compile it) will indeed show the "false" line.
The compiler complains because the left half class == 'a'
"does nothing": it has no side effect on class
or on the result of the if
statement. Thus, the compiler assumes this is a mistake and therefore issues the warning. It is a warning and not an error, because the syntax is correct. For comparison, you are allowed to write something similar such as
if (class = 'a', 'A')
printf ("class == a,A seems to be true\n");
else
printf ("That didn't work.\n");
which has a valid side effect (class
gets the value for the character constant 'a'
) -- but it also will always state that it appears to be true, because the second half is what is passed on to the if
statement.
¹ For C, I use true
and false
in the boolean sense only, as C has by default no concept of these named values without including stdbool.h
(this defines the constants by name). The underlying concept is the same, though: an if
statement evaluates its parameter, which is considered false
if it evaluates to 0
(and thus will not execute the following expression), true
if it evaluates to anything else than 0
.