【问题标题】:unexpected behaviour of pre and post increment in c language gcc compiler [duplicate]c语言gcc编译器中前后增量的意外行为[重复]
【发布时间】:2017-10-11 15:40:42
【问题描述】:

如果 n 的值为 5,则输出:

printf("%d %d", n++, ++n); //should be 5 and 7

但我得到的是输出 6 和 7。

【问题讨论】:

  • 请阅读序列点的规则。这种行为绝对是出乎意料的。在函数调用期间,您不应更改变量的值超过 1 次。
  • 意外行为实际上,这是未定义的行为。函数参数的求值顺序没有定义。

标签: c output increment post-increment pre-increment


【解决方案1】:

对这种未定义的行为造成了多次未排序的修改。如果您搜索它,会有大量结果,例如这个question

下次编译时启用所有警告,如下所示:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
main.c:6:22: warning: multiple unsequenced modifications to 'n' [-Wunsequenced]
    printf("%d %d", n++, ++n); 
                     ^   ~~

【讨论】:

    【解决方案2】:

    printf() 调用未定义行为。 请看Undefined Behavior and Sequence Points

    在函数调用参数列表中修改变量值两次或更多次不是一个好习惯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      相关资源
      最近更新 更多