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.
Difference between x++ and x= x+1 in Java programmingx++ automatically handles the type casting where as x= x + 1 needs typecasting in case of x is not an int variable. See the example below.
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 .
You probably learned that x++ is the same as x = x+1 .
x++ and ++x both are increment operator which are used to increase the value of a variable by 1, there is a very slight difference between two. In x++ the value of variable is printed first then it is incremented whereas in ++x the value is incremented first and then it is displayed. hope u understood it.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With