What exactly is the difference between x++ and x+1?
Solution 1
x++ and ++x
The increment operator x++
will modify and usually returns a copy of the old x
. On a side note the prefixed ++x
will still modify x
but will returns the new x
.
In fact x++
can be seen as a sort of:
{
int temp = x;
x = x + 1;
return temp;
}
while ++x
will be more like:
{
x = x + 1;
return x;
}
x + 1
The x+1
operation will just return the value of the expression and will not modify x
. And it can be seen as:
{
return (x + 1);
}
Solution 2
x++
is an action in the sense that it changes x
x+1
does not change x
Solution 3
x++
is a const expression that modifies the value of x
(It increases it by 1
). If you reference x++
, the expression will return the value of x
before it is incremented.
The expression ++x
will return the value of x
after it is incremented.
x + 1
however, is an expression that represents the value of x + 1
. It does not modify the value of x
.
Solution 4
a++ will translate to a=a+1 which is an action (due to the contained assignment operation) a+1 is just an expression which refers to a+1 (either in pointer terms or in terms of a number depending upon a's type)
Solution 5
x++ is equivalent to x = x + 1. It is an action in that it is actually changing the value of x.
Comments
-
syk435 almost 2 years
I've been thinking about this in terms of incrementing a pointer, but i guess in general now I don't know the semantic difference between these two operations/ operators. For example, my professor said that if you have int a[10] you can't say a++ to point at the next element, but I know from experience that a+1 does work. I asked why and he said something like "a++ is an action and a+1 is an expression". What did he mean by it's an "action"? If anyone could tell me more about this and the inherent difference between the two operations I'd greatly appreciate it. Thank you.