简体   繁体   English

'if' 语句中的赋值和比较顺序

[英]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? C 标准对要打印的内容有什么规定? 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: §6.8.4 说if选择语句的语法是:

if ( expression ) statement

Further in this section, it mentions that if the expression compares unequal to 0, then statement is executed.在本节中,它提到如果表达式比较不等于 0,则执行statement 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:因此,必须先计算表达式,然后才能将其与 0 进行比较i = 0是计算结果为 0 的表达式。有关进一步的参考,请参阅第 6.5.16 节“赋值运算符”的第 6.5 节“表达式”,特别注意这段摘录:

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.赋值表达式返回分配的值,因此表达式的计算结果为 false。

i=0 evaluates to 0 thus the output will not happen. i=0评估为 0,因此不会发生输出。

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.相关的是i=0作为表达式的值,它被定义为值为 0。

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

The expression of the if clause is evaluated first, the result of which is 0.先计算 if 子句的表达式,结果为 0。

This program will never print "Got here\n".这个程序永远不会打印“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) .如果您希望打印该语句,则必须使用if (i = -1)

Nothing will print.什么都不会打印。 The 0 get assigned to i and then that value is tested for the condition.将 0 分配给 i ,然后对该值进行条件测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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