C编程:运算符优先级之间的混淆 [英] C Programming : Confusion between operator precedence

查看:83
本文介绍了C编程:运算符优先级之间的混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对运算符的优先级感到困惑,想知道如何评估该语句.

I am confused between precedence of operators and want to know how this statement would be evaluated.

# include <stdio.h>

int main()
{
  int k=35;  
  printf("%d %d %d",k==35,k=50,k>40);  
  return 0;  
}

这里k最初的值为35,当我在printf中测试k时,我认为:

Here k is initially have value 35, when I am testing k in printf I think :

    应该检查
  1. k>40,结果应为0
  2. 应该检查
  3. k==35,结果应为1
  4. 应将近50个分配给k,并应将其输出50个
  1. k>40 should be checked which should result in 0
  2. k==35 should be checked and which should result in 1
  3. Lastly 50 should get assigned to k and which should output 50

因此最终输出应为1 50 0,但输出为0 50 1.

So final output should be 1 50 0, but output is 0 50 1.

推荐答案

由于该程序的输出 undefined behavior ,未在C语言中指定评估顺序,因为这样可以使编译器更好地进行优化,请参见C99标准草案条款6.5段落3:

You can not rely on the output of this program since it is undefined behavior, the evaluation order is not specified in C since that allows the compiler to optimize better, from the C99 draft standard section 6.5 paragraph 3:

运算符和操作数的分组由语法指示.74)除非指定 稍后(对于函数调用(),&,||,?:和逗号运算符),子表达式的评估顺序和发生副作用的顺序均未指定. strong>

The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

它也是未定义的,因为您正在访问k的值并在同一 sequence point .从标准节6.5的段落2:

It is also undefined because you are accessing the value of k and assigning to it in the same sequence point. From draft standard section 6.5 paragraph 2:

在上一个序列点和下一个序列点之间,对象应具有其存储值 通过对表达式的求值最多只能修改一次. 此外,先前的价值 只能读取以确定要存储的值.

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

它引用了以下未定义的代码示例:

it cites the following code examples as being undefined:

i = ++i + 1;
a[i++] = i; 

更新

有人评论函数调用中的逗号是否充当序列点.如果我们查看6.5.17 Comma operator部分,则2段落说:

There was a comment as to whether the commas in the function call acted as a sequence point or not. If we look at section 6.5.17 Comma operator paragraph 2 says:

逗号运算符的左操作数被评估为void表达式; 有一个 评估后的序列点.

The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation.

但段3说:

示例如语法所示,逗号操作符(如本小节中所述)不会出现在使用逗号分隔列表项(例如函数的参数或初始化器列表)的上下文中).

因此在这种情况下,逗号不会引入序列点.

So in this case the comma does not introduce a sequence point.

这篇关于C编程:运算符优先级之间的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆