英文:
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 << y;
答案1
得分: 5
你不能确定--x
和x--
哪个先被计算,所以结果是未定义的。
英文:
You are not guaranteed whether --x
or x--
is evaluated first, so the result is undefined.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论