Trying to understand –x vs x– in C++

huangapple go评论101阅读模式
英文:

Trying to understand --x vs x-- in C++

问题

我正在尝试评估这个问题,尽管它很简单,但我似乎无法理解。我得到的答案是16,但提供的答案是12。我不明白这怎么可能是12。

我首先执行了--x,所以y的值应该是4,然后我需要与x--相乘,但由于它是在之后评估的,所以它的值也是4,然后x被递减为3。所以4*4=16

有人能解释一下我的推理有什么问题吗?

int x, y;
x = 5;
y = --x * x--;
std::cout << y;
英文:

I am trying to evaluate this, and even if is is quite simple, I can't seem to understand it. I got 16, but the provided answer was 12. I don't understand how this can be 12.

I did --x first, so first y would be 4, then I need to multiply with x--, but it will be 4 too since it is evaluated after, and the x being decremented after that to 3. So 4*4 = 16.

Can someone explain what is wrong in my reasoning?

int x, y;
x = 5;
y = --x * x--;
std::cout &lt;&lt; y;

答案1

得分: 5

你不能确定--xx--哪个先被计算,所以结果是未定义的。

英文:

You are not guaranteed whether --x or x-- is evaluated first, so the result is undefined.

huangapple
  • 本文由 发表于 2023年8月9日 02:08:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定