tags:

views:

159

answers:

9

Looking at the code:

int i = 5;
if (i = 0)
{
  printf ("Got here\n");
}

What does the C standard have to say about what will get printed? Or in more general terms does the assignment happen first or the comparison?

+1  A: 

The assignment happens, which returns a 0, which is false.

Ignacio Vazquez-Abrams
+5  A: 

Assignment first, as it is part of the evaluation. The expression of the assignment returns the assigned value, so the expression evaluates as false.

iniju
Any reference to the standard?
doron
I don't know which part of the standard you want quoted... assignments are expressions, and an `if` must evaluate its expression prior to determining the truth of that expression (by definition).
rmeador
A: 

The expression of the if clause is evaluated first, the result of which is 0.

This program will never print "Got here\n".

nos
+3  A: 

i=0 evaluates to 0 thus the output will not happen.

The prior assignment (the first line of source code) is irrelevant to the outcome.

Steve Townsend
Yes there is, i is checked for truth. If i is set to zero before the comparison, then we do not print Got here, if the comparison happens first we do.
doron
@doron - show me which line of code is the comparison, and I will edit accordingly. Thanks
Steve Townsend
@Steve, the C standard says that the expression itself is compared to 0, and that the substatement of an `if` selection statement is only executed if the expression compares unequal to 0. I think @doron wants to know whether the comparison occurs after or before the assignment.
dreamlax
The value expression `i=0` is compared to `0`. There definitely is a comparison here.
John Dibling
@John - thanks, edited accordingly. Still don't understand the part where 'i is checked for truth'.
Steve Townsend
+2  A: 

The statement i = 0 will be evaluated and return 0, so the statement will not be printed.

Philip Starhill
A: 

As others already said, the assignment returns the value of that is assigned and so never prints the statement. If you wanted the statement to be printed, you'd have to use if (i = -1).

schnaader
A: 

Nothing will print. The 0 get assigned to i and then that value is tested for the condition.

Babak Naffas
+8  A: 
dreamlax
+2  A: 

When the assignment happens is irrelevant. What's relevant is the value of i=0 as an expression, and it's defined to have the value 0.

R..