为什么这些构造使用前后递增的未定义行为? [英] Why are these constructs using pre and post-increment undefined behavior?

查看:104
本文介绍了为什么这些构造使用前后递增的未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main(void)
{
   int i = 0;
   i = i++ + ++i;
   printf("%d\n", i); // 3

   i = 1;
   i = (i++);
   printf("%d\n", i); // 2 Should be 1, no ?

   volatile int u = 0;
   u = u++ + ++u;
   printf("%d\n", u); // 1

   u = 1;
   u = (u++);
   printf("%d\n", u); // 2 Should also be one, no ?

   register int v = 0;
   v = v++ + ++v;
   printf("%d\n", v); // 3 (Should be the same as u ?)

   int w = 0;
   printf("%d %d\n", ++w, w); // shouldn't this print 1 1

   int x[2] = { 5, 8 }, y = 0;
   x[y] = y ++;
   printf("%d %d\n", x[0], x[1]); // shouldn't this print 0 8? or 5 0?
}

推荐答案

C具有未定义行为的概念,即某些语言构造在语法上是有效的,但您无法在代码运行时预测其行为.

C has the concept of undefined behavior, i.e. some language constructs are syntactically valid but you can't predict the behavior when the code is run.

据我所知,该标准并未明确说明为什么存在未定义行为的概念.在我看来,这仅仅是因为语言设计人员希望语义上有一些余地,而不是要求所有实现以完全相同的方式处理整数溢出,这很可能会带来严重的性能损失,他们只是放弃了行为未定义,因此,如果您编写导致整数溢出的代码,则可能会发生任何事情.

As far as I know, the standard doesn't explicitly say why the concept of undefined behavior exists. In my mind, it's simply because the language designers wanted there to be some leeway in the semantics, instead of i.e. requiring that all implementations handle integer overflow in the exact same way, which would very likely impose serious performance costs, they just left the behavior undefined so that if you write code that causes integer overflow, anything can happen.

因此,考虑到这些原因,为什么会出现这些问题"?该语言清楚地表明,某些事情会导致未定义行为.没问题,没有应该"参与.如果在所涉及的变量之一声明为volatile时未定义的行为发生了变化,则不会证明或更改任何内容.它是 undefined ;您无法对此行为进行推理.

So, with that in mind, why are these "issues"? The language clearly says that certain things lead to undefined behavior. There is no problem, there is no "should" involved. If the undefined behavior changes when one of the involved variables is declared volatile, that doesn't prove or change anything. It is undefined; you cannot reason about the behavior.

您看起来最有趣的示例,

Your most interesting-looking example, the one with

u = (u++);

是未定义行为的教科书示例(请参见Wikipedia在序列点上的条目).

is a text-book example of undefined behavior (see Wikipedia's entry on sequence points).

这篇关于为什么这些构造使用前后递增的未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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