multiple choice q/a doubt

buddy's Avatar, Join Date: Aug 2007
Go4Expert Member
Code:
int z,x=5,y=-10,a=4,b=2; z=x++ - --y*a/b
for this program the answer was given as 12 but when i tried to run this program it gave output of 10.

Can any one explain this?? i saw this code in a thread heading 100 multiple choice questions.
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
Neither of your answers is correct. Perhaps you copied the code incorrectly. You certainly have an error in the posted material: a missing semicolon.

Cramming a bunch stuff on one line is not good practice. It doesn't make your code shorter. It doesn't make your code faster. It doesn't make your code more readable. It's the act of a novice or a schlock.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Try evaluating and see what is the order and then try to come up with an explanation that the compiler is behaving in such a manner.

Also if you have some thing else as the answer the original answer could be wrong also.
0
buddy's Avatar, Join Date: Aug 2007
Go4Expert Member
hi dawei&shabbir,

first i had writen code in code block for first time so this kind of confusion,actually i had written code in both Turboc++ and UNIX in step by step only without any error.it compiled without error.Both gave output of 10.can u plz explain the equation,what will happen when z=x++ - --y*a/b; executes.???

Plz.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
I also Ran and saw that it should be 10. Need to make that correct in that thread.
0
buddy's Avatar, Join Date: Aug 2007
Go4Expert Member
[CODE]Z = x++ - --y*b/a;
Z= 5++ - -- -10*2/4;
Z= 10;

Thank you shabbir,but in second line -- -20/4 gives -5 which is decremented to -6 then,x++ increments but remains 5 then the answer should be 11.why was it giving 10.??
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
The first expression, x++, will evaluate to 5 because it isn't incremented until afterwards.
The second expression, --y, will evaluate to -11.
The multiplication will be performed before the subtraction, thus -11 * 4 / 2 = -22
Then, 5 - -22 = 27.

If you compile and run the code, you will get 27.

Code:
#include<iostream>
using std::cout;
using std::endl;

int main()
{
    int z,x=5,y=-10,a=4,b=2; z=x++ - --y*a/b;
    cout << "The result is " << z << endl;
    return 0;
}
Quote:
Originally Posted by Output
The result is 27
0
buddy's Avatar, Join Date: Aug 2007
Go4Expert Member
hi dawei,

Thanks for your help.i will execute the code and get back to you tomorrow.bye
0
buddy's Avatar, Join Date: Aug 2007
Go4Expert Member
hi DaWei,

i have executed your code understood well .Thanks for your explaination.

Regards.