Reputation: 2541
I found a bug in code (the if statement should have had "==" instad of "=") and I have few questions.
Example code:
int i = 5;
if (i = MyFunction()) // MyFunction() returns an int; this is where bug was made
{
// call A()
}
else
{
// call B()
}
From what I gather it should always call A().
1. Is my assumption correct()?
2. Is this case for all/most compilers (any exceptions)?
Upvotes: 1
Views: 12870
Reputation: 399743
A()
if the assignment is considered true, i.e. non-zero.Some people flip comparisons, writing the constant to the left, to avoid the risk:
if( 12 == x )
but of course this wouldn't have worked in your case, since it really is an assignment. Most compilers can give you a warning when this code is detected, since it's so often a cause of bugs.
Upvotes: 8
Reputation: 21351
You code will evaluate
(i = MyFunction())
and if MyFunction()
returns a non zero value, the expression will be evaluated as true and call A()
. Otherwise B()
Upvotes: 2
Reputation: 28268
Your assumption is incorrect.
The expression in the if
-condition is evaluated like any other expression, in your case the result of (i = MyFunction())
is the return value of MyFunction()
.
Upvotes: 3
Reputation: 1031
This statement is an assignment:
i = MyFunction()
The if statement is in effect checking the value of i. If MyFunction() returns 0, i is assigned 0 and it becomes equivalent to:
if(0)
This evaluates to false, and A() will not be called in this case
Upvotes: 4
Reputation: 157314
If MyFunction()
returns zero (0
) it will call B(); otherwise it will call A(). The value of an assignment expression is the value that is assigned to the left hand side; in an if
statement 0 is treated as false and all other values as true.
This is perfectly legitimate code, although many compilers will issue a warning. The reason it is valid is that in C and similar languages, assignment is an expression (rather than a statement).
If you intended to assign to i
and test the return value you should write if ((i = MyFunction()))
; the extra parentheses signal to the compiler (and to the reader) that the assignment is intended.
If instead you intend to test against the value of i
you should write if (MyFunction() == i)
; by putting the function call on the left you ensure that if you miss out the double equals sign the code will fail to compile (MyFunction() = i
is not usually a valid expression).
Upvotes: 6
Reputation: 34408
It will take the true branch (i.e. call A
) if the function return is non-zero. Zero is treated as false so if MyFunction()
returns zero it will call B
instead.
In practice, yes this is correct for most / all compilers. I think 0=false was just a convention; I wouldn't be surprised if it is now formalised in C99 or later but I don't have a copy handy to refer you to the right section.
Upvotes: 3