#include <stdio.h>
int main()
{
int x=100;
x=x++;
printf("x : %d\n",x); //prints 101
return 0;
}
What is the reason for output 101? I think output should be 100.
#include <stdio.h>
int main()
{
int x=100;
x=x++;
printf("x : %d\n",x); //prints 101
return 0;
}
What is the reason for output 101? I think output should be 100.
This is Undefined Behaviour, due to Sequence Points.
Between consecutive "sequence points" an object's value can be modified only once by an expression
The end of the previous epxression x=100;
is one sequence point, and the end of x=x++;
is another.
Basically, your expression has no intermediate 'sequence points', yet you're modifying the value of X twice. the result of this is Undefined Behaviour: Basically, anything could happen: You could get 100, 101 or 42...
Here is what I believe you're looking for:
int main(){
int x=100;
printf("x : %d\n",x++); // Will print 100 and then increment x
return 0;
}
You're incrementing x
before printing it - so this is the reason for the output 101
.
You're doing the same operations as x = x; x++;
You're incrementing x
after assigning it to x
, effectively:
The x=x++
effectively becomes (assign x to x prior to increment) then (increment x)
This is going to give the same effect as if you were to wrote:
x = x;
++x; // Increment after the assignment
This should leave x as 101 after the x=x++;
line.
You're incrementing the same x
you're printing - here it doesn't matter whether post- or pre-incrementing.
x=x++
would produce the same result as x=++x
.
If you would like to assign it another object do this:
#include<stdio.h>
int main(){
int x=100;
int y=x++;
printf("y : %d\n",y); //prints 100
printf("x : %d\n",x); //prints 101
return 0;
}
This is what is happening
#include <stdio.h>
int main()
{
int x=100;
x=x++; // This is original code however I have rewritten this as below
x=x;
x++;
printf("x : %d\n",x); //prints 101
return 0;
}
as you can see
x=x++;
can be rewritten as
x=x;
x++;
hence the result no surprises ...
The effect is that the value of x won't change.
x++
works like this:
In C++ it would look like this:
int PostIncrement(int& x)
{
int y = x;
x = x + 1;
return y;
}
The operator precedence is not lost in this way and the assignment is done after the increment.