Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment and comparison

Tags:

c++

c

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?

like image 654
doron Avatar asked Nov 28 '22 19:11

doron


2 Answers

§6.8.4 says that the syntax for an if selection statement is:

if ( expression ) statement

Further in this section, it mentions that if the expression compares unequal to 0, then statement is executed. The expression must therefore be evaluated before it can be compared to 0. i = 0 is an expression which evaluates to 0. For further reference, see §6.5 “Expressions” with regards to §6.5.16 “Assignment operators”, in particular note this excerpt:

An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue.

like image 65
dreamlax Avatar answered Dec 05 '22 02:12

dreamlax


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

like image 32
iniju Avatar answered Dec 05 '22 01:12

iniju