| aswin1993 (4) | |
|
hi... can anyone say the reason for the different output that i get for the same expression... int a =5; int x; x=++a+a; int y=++a+a; | |
|
|
|
| helios (9442) | |||
Those two lines have undefined behavior. You shouldn't use a variable that you're in/decrementing in the same expression you're in/decrementing it. Or are you asking about what ++a does? | |||
|
|
|||
| MFserver (5) | |
|
Your third row (x=++a+a;), means "a plus one plus a", which in this case is 5 + 1 + 6. Your fourth row means the same, "a plus one plus a", but the difference is that a is now holding 6, not 5. That's why you are getting different output. Your third row is equal to 6 + 1 + 7, which is not equal to 5 + 1 + 6. | |
|
|
|
| aswin1993 (4) | |
|
oops .. That wasnt my question.... I typed it wrongly... Try this code..... I got a different output..... #include<iostream.h> void main() { int a,b,x; a=5; b=5; x= a + a++; int y= b+ b++; cout<<a<<b; } output was 10 11.... for the same operation two different output came.... anyone knows abt this? | |
|
|
|
| hannes (97) | |
| You output can't be 10 and 11, my output is 6 and 6. | |
|
|
|
| melkiy (131) | ||
The order in which compiler estimates operands is undefined, as far as i know. So if the first operand is calculated before (a) and the second - later (a++), than you would obtain 5+5 = 10. But if the second operand is calculated first, you obtain 6(new value) + 5 = 11. You should not write the code with undefined behaviour. Also, do not use such things in function calls like f(a, a++) for the same reason.
| ||
|
|
||
| gcampton (859) | ||||
I did that in my head and got 10 10 but compiled and got 6 6 aswin you might want to try not using depreciated headers instead use this: additionally you need to declare your 'using std::cout' or use std::cout.
| ||||
|
Last edited on
|
||||
| aswin1993 (4) | |
|
sorry...i didnt write it correctly... I was asking about the value of x and y .... | |
|
|
|
| helios (9442) | |||
| |||
|
|
|||
| aswin1993 (4) | |
| okay... thank you... | |
|
|
|