int main()
{
int a = INT_MAX;
a=a<<1;
cout<<a<<endl;
cout<<++a<<endl;
a=a++;
cout <<a<<endl;
return 0;
}
Now the output it is showing is :
2147483647
-2
-1
-1
the last value should be 0 according to me. why is it -1?
int main()
{
int a = INT_MAX;
a=a<<1;
cout<<a<<endl;
cout<<++a<<endl;
a=a++;
cout <<a<<endl;
return 0;
}
Now the output it is showing is :
2147483647
-2
-1
-1
the last value should be 0 according to me. why is it -1?
why last one should be 0??
the final output is -1 . I wanted to know why it should be -1 and not 0.
Hey @abhaysota
The assignment operator ( =
) has lower precedence than any primary operator, such as ++x
or x++
. That means that in the line
a=-1;
a = a++;
the right hand side is evaluated first. The expression a++
increments a
to 0, then returns the original value -1
as a result, which is used for the assignment.
In other words, your code is equivalent to
// Evaluate the right hand side:
int incrementResult = a; // Store the original value, int incrementResult = -1
a = a + 1; // Increment a, i.e. a = 0
// Perform the assignment:
a = incrementResult; // Assign c to the "result of the operation", i.e. a = -1
Compare this to the prefix form
a = ++a;
which would evaluate as
// Evaluate the right hand side:
a = a + 1; // Increment a, i.e. a = 0
int incrementResult = a; // Store the new value, i.e. int incrementResult = 0
// Perform the assignment:
a = incrementResult; // Assign c to the "result of the operation", i.e. a=0