Different output for same expression

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;
1
2
x=++a+a;
int y=++a+a;

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?
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.
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?
You output can't be 10 and 11, my output is 6 and 6.
x= a + a++;


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.
You output can't be 10 and 11, my output is 6 and 6.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
// using std::cout;

int main()
{
    int a,b,x;
  
    a=5;
    b=5;
    x= a + a++;
    int y= b+ b++;
    std::cout << a << " " << b;
// or std::cout << a << " " << b;
// if not decalred as using.
   
    return 0;
}
Last edited on
sorry...i didnt write it correctly...

I was asking about the value of x and y ....
helios wrote:
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.
okay... thank you...
Topic archived. No new replies allowed.