为什么(c ++)*(c ++)在C ++中是未定义的行为? [英] Why is (c++)*(c++) undefined behavior in C++?

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

问题描述

我对这段代码的输出感到困惑:

I am confused about the output of this code:

int c=3;
cout<<(c++)*(c++);

我使用gcc,输出为 9 ,但有人说这是未定义的行为,为什么?

I use gcc and the output is 9, but someone said that it's undefined behavior, why?

推荐答案

问题是序列点:

http://en.wikipedia.org/wiki/Sequence_point


命令式编程中的顺序点定义了
计算机程序执行中保证所有$先前评估的b $ b效应将被执行,随后评估中的副作用
尚未被执行。

A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.

当同一变量在单个表达式中被多次修改
。一个经常被引用的例子是C表达式i = i ++的
,显然它既为i赋了其先前的
值,又使i递增。 i的最终值不明确,因为
取决于表达式求值的顺序,增量
可能在赋值之前,之后或与赋值交错。特定语言的
定义可以指定可能的
行为之一,或者只是说该行为未定义。在C和C ++中,
评估这样的表达式会产生不确定的行为。[1]

Sequence points also come into play when the same variable is modified more than once within a single expression. An often-cited example is the C expression i=i++, which apparently both assigns i its previous value and increments i. The final value of i is ambiguous, because, depending on the order of expression evaluation, the increment may occur before, after, or interleaved with the assignment. The definition of a particular language might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior.[1]

碰巧,我得到的正是在MSVC(Windows)和gcc(Linux)上都使用相同的答案- 9。我还会收到是否使用gcc( C)或g ++(C ++)进行编译的警告:

As it happens, I get exactly the same answer - "9" - on both MSVC (Windows) and gcc (Linux). I also get a warning whether I compile with gcc ("C") or g++ (C++):

$ g++ -o tmp -Wall -pedantic tmp.cpp
tmp.cpp: In function "main(int, char**)":
tmp.cpp:7: warning: operation on "c" may be undefined
$ ./tmp
c=9...

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

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