C 编程 : Confusion between operator precedence

标签 c operators operator-precedence

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

# include <stdio.h>

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

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

  1. k>40 应检查结果应为 0
  2. k==35 应该被检查并且结果应该是 1
  3. 最后 50 应该分配给 k 并且应该输出 50

所以最终输出应该是1 50 0,但是输出是0 50 1

最佳答案

你不能依赖这个程序的输出,因为它是 undefined behavior ,在 C 中未指定评估顺序,因为这允许编译器更好地优化,来自 C99 草案标准部分 6.5 段落 3:

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:

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.

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

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

更新

关于函数调用中的逗号是否充当序列点有评论。如果我们看一下 6.5.17 Comma operator 段落 2 说:

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

但是段落 3 说:

EXAMPLE As indicated by the syntax, the comma operator (as described in this subclause) cannot appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists of initializers).

所以在这种情况下,逗号不会引入序列点。

关于C 编程 : Confusion between operator precedence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18231716/

相关文章:

c - 警告 : format '%lu' expects argument of type 'long unsigned int' , 但参数 4 的类型为 'long unsigned int *' [-Wformat]

不会添加 C 变量

xpath - Xpath |路径内的运算符

c++ - << 运算符与 C++ 中字符串的重载 + 运算符

Javascript 或表达式 : return Operand that is *not* NaN

sql - 在 PostgreSQL 中分组 AND 和 OR 条件

c - C 中的双指针常量正确性警告

c - 输入 fget 时检测到堆栈崩溃

c++ - 按值显式复制构造函数或隐式参数

sql - 在 SQL 中,在 OR 中使用括号是什么意思?