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

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

问题描述

#include <stdio.h>

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

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

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

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

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

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

   int x[2] = { 5, 8 }, y = 0;
   x[y] = y ++;
   printf("%d %d
", 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 时未定义的行为发生了变化,那并不能证明或改变任何事情.它是未定义;你无法对这种行为进行推理.

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天全站免登陆