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.
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.
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.
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.
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.??
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; }