Question:
Today I saw a strange if construct in the code:
#define ERROR_OK 0L
int foo();
// ...
if (ERROR_OK == foo() != ERROR_OK)
{
// ...
}
else
{
// ...
}
So I didn’t fully understand why this code works and at what values the function is executed. I realized that if foo() returns 0, then the branch inside the if will be executed. Please help me understand completely.
Answer:
Well, it's pretty simple. Let's take it apart piece by piece.
1) ERROR_OK == foo()
is compared. It will return true
or false
, depending on the value of ERROR_OK
and what the function returns.
2) The result of the previous calculation (i.e. true
or fals
e) is compared with ERROR_OK
. In this case, the same true
or false
will be reduced to int
(true -> 1, false -> 0)
. Well, the usual comparison.
Accordingly, if we assume that ERROR_OK = 0
(and it is written that way in the condition), then the first part of the condition is equivalent to 0 == foo()
, i.e. !foo()
. The second part of the condition is equivalent to !foo() != 0
, i.e. foo() == 0
, i.e. just !foo()
. This means that if foo
returns 0
, then the condition will be met, otherwise it won't.