c - 奇怪的C优先级评估

标签 c operator-precedence

有人可以解释一下这段代码中的优先级发生了什么吗?我一直试图弄清楚自己到底发生了什么,但我无法独自处理。

#include <stdio.h>

int main(void) {
   int v[]={20,35,76,80};
   int *a;
   a=&v[1];
   --(*++a);

  printf("%d,%d,%d,%d\n",v[0],v[1],v[2],v[3]);

  (*++a);

  printf("%d\n", *a);

  *a--=*a+1; // WHAT IS HAPPENING HERE?

  printf("%d\n", *a);

  printf("%d,%d,%d,%d\n",v[0],v[1],v[2],v[3]);

}


//OUTPUT
20,35,75,80
80
75
20,35,75,76

最佳答案

*a--=*a+1; // WHAT IS HAPPENING HERE?

所发生的情况是行为未定义

6.5 Expressions
...
2    If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.84)

3    The grouping of operators and operands is indicated by the syntax.85) Except as specified later, side effects and value computations of subexpressions are unsequenced.86)

C 2011 Online Draft (N1570)

表达式*a--*a 彼此之间无序。除少数情况外,C 不保证表达式从左到右计算;因此,不能保证 *a--*a 之前进行评估(并应用副作用)。

*a-- 有一个副作用 - 它更新 a 以指向序列中的前一个元素。 *a + 1 是一个值计算 - 它将 a 当前指向的值加 1。

取决于 *a--*a 的计算顺序以及 -- 运算符的副作用实际发生的时间应用后,您可以将 v[1] + 1 的结果分配给 v[0],或将 v[1] + 1 分配给v[1],或 v[0] + 1v[0],或 v[0] + 1v[1],或者完全是其他东西

由于行为未定义,编译器不需要执行任何特定操作 - 它可能发出诊断并停止翻译,它可能发出诊断并完成翻译,或者可能在没有诊断的情况下完成翻译。在运行时,代码可能崩溃,您可能得到意想不到的结果,或者代码可能按预期工作。

关于c - 奇怪的C优先级评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078253/

相关文章:

c - 如何在 C 中使用大于和小于(> 和 <)比较 float

c - opengl,帮助完成 glutmainloop 或函数完成

c - 向链表添加元素(C)

c - 如何将 char 数组重置为 NULL(空)

C 运算符优先级,后增量编程问题

programming-languages - 为什么结合性是运算符的基本属性而不是优先级的基本属性

c++ - 三元运算符的返回类型是如何确定的?

ruby - 使用 Proc.call 与 Proc.[] 是否存在 Ruby 优先级问题?

c - 如何使用 sscanf 检查 argv 参数是否是数字而不是其他内容?

c++ - 这段代码定义明确吗?