How do we explain the result of the expression (++x)+(++x)+(++x)?

前提是你 提交于 2019-11-27 04:39:16
CB Bailey

We explain it by expecting undefined behaviour rather than any particular result. As the expression attempts to modify x multiple times without an intervening sequence point its behaviour is undefined.

Artelius

As others have said, the C and C++ standards do not define the behaviour that this will produce.

But for those people who don't see why the standards would do such a thing, let's go through a "real world" example:

1 * 2 + 3 + 4 * 5

There's nothing wrong with calculating 1 * 2 + 3 before we calculate 4*5. Just because multiplication has a higher precedence than addition doesn't mean we need to perform all multiplication in the expression before doing any addition. In fact there are many different orders you validly could perform your calculations.

Where evaluations have side effects, different evaluation orders can affect the result. If the standard does not define the behaviour, do not rely on it.

This is actually undefined. C++ doesn't define explicitly the order of execution of a statement so it depends on the compiler and this syntax shouldn't be used.

The code snippet will invoke Undefined behavior in both C/C++.Read about Sequence Point from here.

In my opinion

cout<<((++x)+(++x)+(++x));

compiler first run prefix ++x so value of x becomes

x=2


now by ++x, x will become

x=3


after ++x

x=4


Now its time to add values of x

x+x+x=4+4+4

x+x+x=12

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!