简体   繁体   中英

Order of assignment and comparison in an 'if' statement

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?

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

 ( 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.

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

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.

语句i = 0将被评估并返回0 ,因此不会打印该语句。

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.

赋值发生了,它返回一个 0,它是假的。

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

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

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) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM