c - 在 printf 中发布增量和指针

标签 c pointers printf post-increment

<分区>

谁能解释一下为什么这段代码输出 2 1,我认为后增量应该在 printf 指令之后应用。

#include <stdio.h>

int main() {
  int i=1;
  int *p=&i;
  printf("%d %d\n", *p ,i++);

  return 0;
}

最佳答案

的求值顺序是not specified对于标准中的这种情况,您无法确定首先评估 *p 还是 i++C99 draft standard6.5.2.2 Function calls10 中说:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

这也是undefined behavior因为您正在修改 i 并在同一序列点内的另一个表达式中访问 i 的先前值,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.72) Furthermore, the prior value shall be read only to determine the value to be stored

关于c - 在 printf 中发布增量和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18773287/

相关文章:

c - 简单的 Makefile : undefined reference to symbol 'cos@@GLIBC_2.2.5' 问题

java - 格式化输出文件的问题

c - 我如何解释这个简单的 C 代码的输出?

c - 在 C 中打印数组时出错

c - 日期与用户输入日期和文件中的日期进行比较

c++ - 实现安全左移

c - 指向结构打印的指针数组

c++ - 可变大小指针数组

c++ - 将 char* 转换为 int* C++

c - 非阻塞套接字选择在连接后返回 1