为什么这些结构(使用++)未定义的行为? [英] Why are these constructs (using ++) undefined behavior?

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

问题描述

  INT主(INT ARGC,字符** argv的)
{
   INT I = 0;
   I = I + + + +我;
   的printf(%d个\\ N,I); // 3   I = 1;
   I =(我++);
   的printf(%d个\\ N,I); // 2,应为1,不是吗?   挥发性INT U = 0;
   û= U + + + + U;
   的printf(%d个\\ N,U); // 1   U = 1;
   U =(U ++);
   的printf(%d个\\ N,U); // 2还值得一体的,不是吗?   注册INT V = 0;
   V = ++ + + + v的
   的printf(%d个\\ N,V); // 3(应该是一样的,如u?)
}


解决方案

C的未定义行为的概念,即有些语言结构在语法上是有效的,但你不能predict的行为时,code是运行。

据我所知,该标准并没有明确说的为什么的未定义行为的概念存在。在我看来,这只是因为语言的设计者希望有是在语义一些回旋余地,而不是即要求所有实现处理整数溢出完全相同的方式,这将很可能处以严重的性能成本,他们刚刚离开的行为未定义因此,如果你写code,导致整数溢出,任何事情都有可能发生。

因此​​,考虑到这一点,为什么这些问题?语言清楚地说,有些事情导致未定义行为。这是没有问题,也没有应该参与其中。如果在所涉及的变量之一是宣布未定义行为更改挥发性,这并不证明或改变任何东西。它的未定义的;你不能推理的行为。

您最有趣的前瞻性例如,一个与

  U =(U ++);

是未定义行为教科书的例子(见维基百科上关于序列点)。

int main(int argc, char ** argv)
{
   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 ?)
}

解决方案

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.

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++);

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

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

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