\/\/\/\/\/ C++ question\/\/\/\/\/?

2008-12-18 5:57 am
int x=4,y=9,z;
z=(++x)+(--x)+(x++)+(--y)+(y++)+(--y);
cout<<z;

Why is the output of this 35 ?
Please tell me... when I evaluate like this, i get 37. where am I going wrong :

z=5+4+4+8+8+8
=37


The Visual C++ compiler gives this as 35
and BCC gives 33

Please tell me what is the correct order to evaluate when this question is asked in my exams
更新1:

omg talon ure such an idiot

更新2:

Dav, dude I have evaluated according to your method only man, but the compiler has different ways, I wanna know how does the compiler do it ??

回答 (4)

2008-12-18 6:46 am
✔ 最佳答案
I have no idea how the compilers do it. But as an interesting fact, Java gives out what 37, which accords with what you and I expected. On the other hand, GCC says it should be 35, which is same as Visual C++'s result.
2008-12-18 2:23 pm
What you must understand is that you could get many different answers for a question like this. Because VC++ gave you 35 and BCC gave you 33, gcc and other compilers might give you something else. In C the + operator does not say who gets evaluated first. So this is why you have different answers.

For example if you did, ans = f() + g(), C does not give specfication of who will be called first [f() or g()]. This type of code is what hurts imperative languages like C, they are the result of a side-effect! Especially in this example as the values of x and y are changed they get evaluated differently for many compilers there is no specification.

In general you would never write code like this.
參考: God
2008-12-18 2:17 pm
hey mate,

z=(++x)+(--x)+(x++)+(--y)+(y++)+(--y);

z = (5) + (4) + (4) + (8) + (8) + (8) =37

is equivalent to
x = x + 1
z = x
x = x - 1
z = z + x + x
x = x + 1
y = y - 1
z = z + y + y
y = y+1
y = y - 1
z = z + y

plug in your numbers and you will generate the result,

Hope this helps,

David

hey mate - I'm not sure eh, I thought I was following the standard BOMDAS rules, and as such I agree with your evaluation,
z = (5) + (4) + (4) + (8) + (8) +(8)=37 (which is result in C#)
Maybe consider than only preprocessing is allowed, Thus,
z=(++x)+(--x)+(x++)+(--y)+(y++)+(--y);
z = (5) + (4) + (4) + (8) + (8) + (8) = 37 - incorrect
Consider if only post processing is allowed,
z = (4) + (4) + (4) + (8) + (8) + (8) = 36 - incorrect
Consider no processing on x,y
z = (4) + (4) + (4) + (9) + (9) + (9) = 39 - still incorrect

Not sure mate, the only possibility I can conjugure up is if the compiler converted + -- into +- or -
i.e,
z = (4) - (4) + (4) - (9) + (9) = 4 - still incorrect!

I'm stumped...
2008-12-18 2:04 pm
I would answer 33. Evaluate the prefix operators before the expression that will be assigned to z.
z = 4+4+4+7+7+7 = 33


收錄日期: 2021-05-01 01:00:10
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20081217215752AAiAnYC

檢視 Wayback Machine 備份