Value of y = x + x++ in Java [duplicate] - java

This question already has answers here:
Is there a difference between x++ and ++x in java?
(18 answers)
Java: pre-,postfix operator precedences
(5 answers)
Closed 6 years ago.
Say we have Java code below:
int x = 1;
int y = x + x++;
'Cause the precedence of "postfix-increment" operator is higher than "add" operator. I think x++ should be calculate and evaluated first. Then it comes to x + (x++). So the y should be "new_x(2) + 1 = 3".
Though it turns out "2" instead of "3". Any ideas? Thanks.
This question is greatly different from Is there a difference between x++ and ++x in java?. That question mentions nothing about the operator precedence.
Someone has explained that expression is read from left to right. Does it conflict with the precedence of those operators?
Just as I mentioned before, I think x++ should be calculated first. It seems that I mess up with the "evaluation" and "calculation".

The difference between x++ and ++x is quite evident and known. ++ can be used as preadd (Add 1 and then use x ) or postadd (use x and add 1).
Check this out.
As tested and seen
1. x + x++ will give 2
2. x + ++x will give 3
3. x++ + x will give 3
4. ++x + x will give 4
Now the interesting case here is 2nd and 4th which basically explains pre-add operator.
In these cases, the value of x is incremented first and then used in both the places.
However in case of test 2 the first operand i.e. x is already used up for addition so the answer is 3
while in the test 4 the operand x is first incremented and used in both the operands. This happens because the expressions are evaluated from left to right.

x++ would first return x then increment x.
++x would increment x first then return x.
Therefore :
int y = x + x++; //y (2) = x(1) + x(1, then becomes 2 right after)
int y = x + ++x; //y (3) = x(1) + x(becomes 2 before being returned)

Related

What does * in front of = mean? [duplicate]

This question already has answers here:
Meaning of *= in Java
(4 answers)
Closed 4 years ago.
Hello everyone I have a very simple question that I just don't understand. I've tried googling it but haven't found a clear answer.
What is x after the following statements?
int x = 2;
int y = 1;
x *= y + 1;
I know that the answer is 4 but I don't understand why it is 4. Just need some clarity on what x* means exactly. Thanks!
I think this line is the one why you ask
x *= y + 1;
This is a shorthand for
x = x * (y + 1);
This works also with other operators like - and +, when the first variable is the same as the variable on the left side (which will be assigned).
Of course x is 4, if you don't understand the last statement, you can read it like this
x = x * y + 2
The x*= symbol means x=x* the result of whatever you put after the equals symbol.
x*= y+1 will turn to x = x * (y+1). The expresion you put after equals is evaluated first and then multiplied with x. The result will be cast to the type of the assignment variable (x).

Missing update statement in if statement makes infinite loop [duplicate]

What happens (behind the curtains) when this is executed?
int x = 7;
x = x++;
That is, when a variable is post incremented and assigned to itself in one statement? I compiled and executed this. x is still 7 even after the entire statement. In my book, it says that x is incremented!
x = x++;
is equivalent to
int tmp = x;
x++;
x = tmp;
x does get incremented. But you are assigning the old value of x back into itself.
x = x++;
x++ increments x and returns its old value.
x = assigns the old value back to itself.
So in the end, x gets assigned back to its initial value.
The statement:
x = x++;
is equivalent to:
tmp = x; // ... this is capturing the value of "x++"
x = x + 1; // ... this is the effect of the increment operation in "x++" which
// happens after the value is captured.
x = tmp; // ... this is the effect of assignment operation which is
// (unfortunately) clobbering the incremented value.
In short, the statement has no effect.
The key points:
The value of a Postfix increment/decrement expression is the value of the operand before the increment/decrement takes place. (In the case of a Prefix form, the value is the value of the operand after the operation,)
the RHS of an assignment expression is completely evaluated (including any increments, decrements and/or other side-effects) before the value is assigned to the LHS.
Note that unlike C and C++, the order of evaluation of an expression in Java is totally specified and there is no room for platform-specific variation. Compilers are only allowed to reorder the operations if this does not change the result of executing the code from the perspective of the current thread. In this case, a compiler would be permitted to optimize away the entire statement because it can be proved that it is a no-op.
In case it is not already obvious:
"x = x++;" is almost certainly a mistake in any program.
The OP (for the original question!) probably meant "x++;" rather than "x = x++;".
Statements that combine auto inc/decrement and assignment on the same variable are hard to understand, and therefore should be avoided irrespective of their correctness. There is simply no need to write code like that.
Hopefully, code checkers like FindBugs and PMD will flag code like this as suspicious.
int x = 7;
x = x++;
It has undefined behaviour in C and for Java see this answer. It depends on compiler what happens.
A construct like x = x++; indicates you're probably misunderstanding what the ++ operator does:
// original code
int x = 7;
x = x++;
Let's rewrite this to do the same thing, based on removing the ++ operator:
// behaves the same as the original code
int x = 7;
int tmp = x; // value of tmp here is 7
x = x + 1; // x temporarily equals 8 (this is the evaluation of ++)
x = tmp; // oops! we overwrote y with 7
Now, let's rewrite it to do (what I think) you wanted:
// original code
int x = 7;
x++;
The subtlety here is that the ++ operator modifies the variable x, unlike an expression such as x + x, which would evaluate to an int value but leave the variable x itself unchanged. Consider a construct like the venerable for loop:
for(int i = 0; i < 10; i++)
{
System.out.println(i);
}
Notice the i++ in there? It's the same operator. We could rewrite this for loop like this and it would behave the same:
for(int i = 0; i < 10; i = i + 1)
{
System.out.println(i);
}
I also recommend against using the ++ operator in larger expressions in most cases. Because of the subtlety of when it modifies the original variable in pre- versus post-increment (++x and x++, respectively), it is very easy to introduce subtle bugs that are difficult to track down.
According to Byte code obtained from the class files,
Both assignments increment x, but difference is the timing of when the value is pushed onto the stack
In Case1, Push occurs (and then later assigned) before the increment (essentially meaning your increment does nothing)
In Case2, Increment occurs first (making it 8) and then pushed onto the stack(and then assigned to x)
Case 1:
int x=7;
x=x++;
Byte Code:
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iload_1 [x] //Push 7 onto stack
4 iinc 1 1 [x] //Increment x by 1 (x=8)
7 istore_1 [x] //Pop 7 and store in x
8 return //x now has 7
Case 2:
int x=7;
x=++x;
Byte Code
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iinc 1 1 [x] //Increment x by 1 (x=8)
6 iload_1 [x] //Push x onto stack
7 istore_1 [x] //Pop 8 and store in x
8 return //x now has 8
Stack here refers to Operand Stack, local: x index: 1 type: int
Post Increment operator works as follows:
Store previous value of operand.
Increment the value of the operand.
Return the previous value of the operand.
So the statement
int x = 7;
x = x++;
would be evaluated as follows:
x is initialized with value 7
post increment operator stores previous value of x i.e. 7 to return.
Increments the x, so now x is 8
Returns the previous value of x i.e. 7 and it is assigned back to x, so x again becomes 7
So x is indeed increased but since x++ is assigning result back to x so value of x is overridden to its previous value.
It's incremented after "x = x++;". It would be 8 if you did "x = ++x;".
The incrementing occurs after x is called, so x still equals 7. ++x would equal 8 when x is called
When you re-assign the value for x it is still 7. Try x = ++x and you will get 8 else do
x++; // don't re-assign, just increment
System.out.println(x); // prints 8
because x++ increments the value AFTER assigning it to the variable.
so on and during the execution of this line:
x++;
the varialbe x will still have the original value (7), but using x again on another line, such as
System.out.println(x + "");
will give you 8.
if you want to use an incremented value of x on your assignment statement, use
++x;
This will increment x by 1, THEN assign that value to the variable x.
[Edit]
instead of x = x++, it's just x++; the former assigns the original value of x to itself, so it actually does nothing on that line.
What happens when int x = 7; x = x++;?
ans -> x++ means first use value of x for expression and then increase it by 1.
This is what happens in your case. The value of x on RHS is copied to variable x on LHS and then value of x is increased by 1.
Similarly ++x means -> increase the value of x first by one and then use in expression .
So in your case if you do x = ++x ; // where x = 7
you will get value of 8.
For more clarity try to find out how many printf statement will execute the following code
while(i++ <5)
printf("%d" , ++i); // This might clear your concept upto great extend
++x is pre-increment -> x is incremented before being used
x++ is post-increment -> x is incremented after being used
int x = 7; -> x get 7 value <br>
x = x++; -> x get x value AND only then x is incremented
So this means:
x++ is not equal to x = x+1
because:
int x = 7; x = x++;
x is 7
int x = 7; x = x = x+1;
x is 8
and now it seems a bit strange:
int x = 7; x = x+=1;
x is 8
very compiler dependent!
Most simplest explanation!
This is because ++ after the operand makes post increment it, means first the value got assigned to the variable & then incremented. While if you're expecting x value to be 8 then you should pre increment it like the way mentioned below:
x = x++;
This is the post-increment operator. It should be understood as "Use the operand's value and then increment the operand".
If you want the reverse to happen i.e "Increment the operand and then use the operand's value", you must use the pre-increment operator as shown below.
x = ++x;
This operator first increments the value of x by 1 and then assigns the value back to x.
I think this controversy can be resolved without going into code & just thinking.
Consider i++ & ++i as functions, say Func1 & Func2.
Now i=7;
Func1(i++) returns 7, Func2(++i) returns 8 (everybody knows this). Internally both the functions increment i to 8 , but they return different values.
So i = i++ calls the function Func1. Inside the function i increments to 8, but on completion the function returns 7.
So ultimately 7 gets allocated to i. (So in the end, i = 7)
This is because you used a post-increment operator.
In this following line of code
x = x++;
What happens is that, you're assigning the value of x to x. x++ increments x after the value of x is assigned to x. That is how post-increment operators work. They work after a statement has been executed. So in your code, x is returned first after then it is afterwards incremented.
If you did
x = ++x;
The answer would be 8 because you used the pre-increment operator. This increments the value first before returning the value of x.

Java post-increment and pre increment behaviour

I have a simple Java expression depicted below. Based on Operator Precedence table, I expect that this expression would return division by zero exception (since post-fix increment operator has highest priority) and expect that resulting expression would look like:
2 + 2 + 5 / 0
But result is 7, why ? (By little bit of experimentation I found that all operators are assigned value of 1 for some reason, but this does not make sense to me in case priority table is correct)
int intCountOperator = 0;
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
System.out.println(unaryOperand); // Prints 7
The operator precedence does not control the evaluation order. It controls only how the expression is to be read. For example, since multiplication has a higher precedence than addition, x + y * z is read as x + (y * z), not (x + y) * z. However, it does not change that first x is evaluated, then y and finally z.
Giving a good example with ++ and -- is more difficult, because there is usually only one reading which makes sense. However, you might notice that y - x++ compiles without error (if x and y are numerical variables). If ++ would have had a lower precedence than - it would be evaluated as (x - y)++ which would not compile.
Because of operator precedence, your expression is evaluated as:
(++intCountOperator) + (intCountOperator + (5 / (intCountOperator++)));
but the evaluation order is not changed by it.
The expression is evaluated from left to right :
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
1 + 1 + 5 / 1 = 7
Note that the operators are evaluated in the order you expect, i.e. 1 + 1 + (5/1) = 1 + 1 + 5 = 7, but the operands of all those expressions are evaluated from left to right.
The order of evaluation is from left to right and not right to left. So the result 7 which you are getting is correct.
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
is actually
unaryOperand = 1 + 1 + 5 / 1; = 7

If y = 1 and y = y++, why when I print y is the value 1? [duplicate]

What happens (behind the curtains) when this is executed?
int x = 7;
x = x++;
That is, when a variable is post incremented and assigned to itself in one statement? I compiled and executed this. x is still 7 even after the entire statement. In my book, it says that x is incremented!
x = x++;
is equivalent to
int tmp = x;
x++;
x = tmp;
x does get incremented. But you are assigning the old value of x back into itself.
x = x++;
x++ increments x and returns its old value.
x = assigns the old value back to itself.
So in the end, x gets assigned back to its initial value.
The statement:
x = x++;
is equivalent to:
tmp = x; // ... this is capturing the value of "x++"
x = x + 1; // ... this is the effect of the increment operation in "x++" which
// happens after the value is captured.
x = tmp; // ... this is the effect of assignment operation which is
// (unfortunately) clobbering the incremented value.
In short, the statement has no effect.
The key points:
The value of a Postfix increment/decrement expression is the value of the operand before the increment/decrement takes place. (In the case of a Prefix form, the value is the value of the operand after the operation,)
the RHS of an assignment expression is completely evaluated (including any increments, decrements and/or other side-effects) before the value is assigned to the LHS.
Note that unlike C and C++, the order of evaluation of an expression in Java is totally specified and there is no room for platform-specific variation. Compilers are only allowed to reorder the operations if this does not change the result of executing the code from the perspective of the current thread. In this case, a compiler would be permitted to optimize away the entire statement because it can be proved that it is a no-op.
In case it is not already obvious:
"x = x++;" is almost certainly a mistake in any program.
The OP (for the original question!) probably meant "x++;" rather than "x = x++;".
Statements that combine auto inc/decrement and assignment on the same variable are hard to understand, and therefore should be avoided irrespective of their correctness. There is simply no need to write code like that.
Hopefully, code checkers like FindBugs and PMD will flag code like this as suspicious.
int x = 7;
x = x++;
It has undefined behaviour in C and for Java see this answer. It depends on compiler what happens.
A construct like x = x++; indicates you're probably misunderstanding what the ++ operator does:
// original code
int x = 7;
x = x++;
Let's rewrite this to do the same thing, based on removing the ++ operator:
// behaves the same as the original code
int x = 7;
int tmp = x; // value of tmp here is 7
x = x + 1; // x temporarily equals 8 (this is the evaluation of ++)
x = tmp; // oops! we overwrote y with 7
Now, let's rewrite it to do (what I think) you wanted:
// original code
int x = 7;
x++;
The subtlety here is that the ++ operator modifies the variable x, unlike an expression such as x + x, which would evaluate to an int value but leave the variable x itself unchanged. Consider a construct like the venerable for loop:
for(int i = 0; i < 10; i++)
{
System.out.println(i);
}
Notice the i++ in there? It's the same operator. We could rewrite this for loop like this and it would behave the same:
for(int i = 0; i < 10; i = i + 1)
{
System.out.println(i);
}
I also recommend against using the ++ operator in larger expressions in most cases. Because of the subtlety of when it modifies the original variable in pre- versus post-increment (++x and x++, respectively), it is very easy to introduce subtle bugs that are difficult to track down.
According to Byte code obtained from the class files,
Both assignments increment x, but difference is the timing of when the value is pushed onto the stack
In Case1, Push occurs (and then later assigned) before the increment (essentially meaning your increment does nothing)
In Case2, Increment occurs first (making it 8) and then pushed onto the stack(and then assigned to x)
Case 1:
int x=7;
x=x++;
Byte Code:
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iload_1 [x] //Push 7 onto stack
4 iinc 1 1 [x] //Increment x by 1 (x=8)
7 istore_1 [x] //Pop 7 and store in x
8 return //x now has 7
Case 2:
int x=7;
x=++x;
Byte Code
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iinc 1 1 [x] //Increment x by 1 (x=8)
6 iload_1 [x] //Push x onto stack
7 istore_1 [x] //Pop 8 and store in x
8 return //x now has 8
Stack here refers to Operand Stack, local: x index: 1 type: int
Post Increment operator works as follows:
Store previous value of operand.
Increment the value of the operand.
Return the previous value of the operand.
So the statement
int x = 7;
x = x++;
would be evaluated as follows:
x is initialized with value 7
post increment operator stores previous value of x i.e. 7 to return.
Increments the x, so now x is 8
Returns the previous value of x i.e. 7 and it is assigned back to x, so x again becomes 7
So x is indeed increased but since x++ is assigning result back to x so value of x is overridden to its previous value.
It's incremented after "x = x++;". It would be 8 if you did "x = ++x;".
The incrementing occurs after x is called, so x still equals 7. ++x would equal 8 when x is called
When you re-assign the value for x it is still 7. Try x = ++x and you will get 8 else do
x++; // don't re-assign, just increment
System.out.println(x); // prints 8
because x++ increments the value AFTER assigning it to the variable.
so on and during the execution of this line:
x++;
the varialbe x will still have the original value (7), but using x again on another line, such as
System.out.println(x + "");
will give you 8.
if you want to use an incremented value of x on your assignment statement, use
++x;
This will increment x by 1, THEN assign that value to the variable x.
[Edit]
instead of x = x++, it's just x++; the former assigns the original value of x to itself, so it actually does nothing on that line.
What happens when int x = 7; x = x++;?
ans -> x++ means first use value of x for expression and then increase it by 1.
This is what happens in your case. The value of x on RHS is copied to variable x on LHS and then value of x is increased by 1.
Similarly ++x means -> increase the value of x first by one and then use in expression .
So in your case if you do x = ++x ; // where x = 7
you will get value of 8.
For more clarity try to find out how many printf statement will execute the following code
while(i++ <5)
printf("%d" , ++i); // This might clear your concept upto great extend
++x is pre-increment -> x is incremented before being used
x++ is post-increment -> x is incremented after being used
int x = 7; -> x get 7 value <br>
x = x++; -> x get x value AND only then x is incremented
So this means:
x++ is not equal to x = x+1
because:
int x = 7; x = x++;
x is 7
int x = 7; x = x = x+1;
x is 8
and now it seems a bit strange:
int x = 7; x = x+=1;
x is 8
very compiler dependent!
Most simplest explanation!
This is because ++ after the operand makes post increment it, means first the value got assigned to the variable & then incremented. While if you're expecting x value to be 8 then you should pre increment it like the way mentioned below:
x = x++;
This is the post-increment operator. It should be understood as "Use the operand's value and then increment the operand".
If you want the reverse to happen i.e "Increment the operand and then use the operand's value", you must use the pre-increment operator as shown below.
x = ++x;
This operator first increments the value of x by 1 and then assigns the value back to x.
I think this controversy can be resolved without going into code & just thinking.
Consider i++ & ++i as functions, say Func1 & Func2.
Now i=7;
Func1(i++) returns 7, Func2(++i) returns 8 (everybody knows this). Internally both the functions increment i to 8 , but they return different values.
So i = i++ calls the function Func1. Inside the function i increments to 8, but on completion the function returns 7.
So ultimately 7 gets allocated to i. (So in the end, i = 7)
This is because you used a post-increment operator.
In this following line of code
x = x++;
What happens is that, you're assigning the value of x to x. x++ increments x after the value of x is assigned to x. That is how post-increment operators work. They work after a statement has been executed. So in your code, x is returned first after then it is afterwards incremented.
If you did
x = ++x;
The answer would be 8 because you used the pre-increment operator. This increments the value first before returning the value of x.

What is x after "x = x++"?

What happens (behind the curtains) when this is executed?
int x = 7;
x = x++;
That is, when a variable is post incremented and assigned to itself in one statement? I compiled and executed this. x is still 7 even after the entire statement. In my book, it says that x is incremented!
x = x++;
is equivalent to
int tmp = x;
x++;
x = tmp;
x does get incremented. But you are assigning the old value of x back into itself.
x = x++;
x++ increments x and returns its old value.
x = assigns the old value back to itself.
So in the end, x gets assigned back to its initial value.
The statement:
x = x++;
is equivalent to:
tmp = x; // ... this is capturing the value of "x++"
x = x + 1; // ... this is the effect of the increment operation in "x++" which
// happens after the value is captured.
x = tmp; // ... this is the effect of assignment operation which is
// (unfortunately) clobbering the incremented value.
In short, the statement has no effect.
The key points:
The value of a Postfix increment/decrement expression is the value of the operand before the increment/decrement takes place. (In the case of a Prefix form, the value is the value of the operand after the operation,)
the RHS of an assignment expression is completely evaluated (including any increments, decrements and/or other side-effects) before the value is assigned to the LHS.
Note that unlike C and C++, the order of evaluation of an expression in Java is totally specified and there is no room for platform-specific variation. Compilers are only allowed to reorder the operations if this does not change the result of executing the code from the perspective of the current thread. In this case, a compiler would be permitted to optimize away the entire statement because it can be proved that it is a no-op.
In case it is not already obvious:
"x = x++;" is almost certainly a mistake in any program.
The OP (for the original question!) probably meant "x++;" rather than "x = x++;".
Statements that combine auto inc/decrement and assignment on the same variable are hard to understand, and therefore should be avoided irrespective of their correctness. There is simply no need to write code like that.
Hopefully, code checkers like FindBugs and PMD will flag code like this as suspicious.
int x = 7;
x = x++;
It has undefined behaviour in C and for Java see this answer. It depends on compiler what happens.
A construct like x = x++; indicates you're probably misunderstanding what the ++ operator does:
// original code
int x = 7;
x = x++;
Let's rewrite this to do the same thing, based on removing the ++ operator:
// behaves the same as the original code
int x = 7;
int tmp = x; // value of tmp here is 7
x = x + 1; // x temporarily equals 8 (this is the evaluation of ++)
x = tmp; // oops! we overwrote y with 7
Now, let's rewrite it to do (what I think) you wanted:
// original code
int x = 7;
x++;
The subtlety here is that the ++ operator modifies the variable x, unlike an expression such as x + x, which would evaluate to an int value but leave the variable x itself unchanged. Consider a construct like the venerable for loop:
for(int i = 0; i < 10; i++)
{
System.out.println(i);
}
Notice the i++ in there? It's the same operator. We could rewrite this for loop like this and it would behave the same:
for(int i = 0; i < 10; i = i + 1)
{
System.out.println(i);
}
I also recommend against using the ++ operator in larger expressions in most cases. Because of the subtlety of when it modifies the original variable in pre- versus post-increment (++x and x++, respectively), it is very easy to introduce subtle bugs that are difficult to track down.
According to Byte code obtained from the class files,
Both assignments increment x, but difference is the timing of when the value is pushed onto the stack
In Case1, Push occurs (and then later assigned) before the increment (essentially meaning your increment does nothing)
In Case2, Increment occurs first (making it 8) and then pushed onto the stack(and then assigned to x)
Case 1:
int x=7;
x=x++;
Byte Code:
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iload_1 [x] //Push 7 onto stack
4 iinc 1 1 [x] //Increment x by 1 (x=8)
7 istore_1 [x] //Pop 7 and store in x
8 return //x now has 7
Case 2:
int x=7;
x=++x;
Byte Code
0 bipush 7 //Push 7 onto stack
2 istore_1 [x] //Pop 7 and store in x
3 iinc 1 1 [x] //Increment x by 1 (x=8)
6 iload_1 [x] //Push x onto stack
7 istore_1 [x] //Pop 8 and store in x
8 return //x now has 8
Stack here refers to Operand Stack, local: x index: 1 type: int
Post Increment operator works as follows:
Store previous value of operand.
Increment the value of the operand.
Return the previous value of the operand.
So the statement
int x = 7;
x = x++;
would be evaluated as follows:
x is initialized with value 7
post increment operator stores previous value of x i.e. 7 to return.
Increments the x, so now x is 8
Returns the previous value of x i.e. 7 and it is assigned back to x, so x again becomes 7
So x is indeed increased but since x++ is assigning result back to x so value of x is overridden to its previous value.
It's incremented after "x = x++;". It would be 8 if you did "x = ++x;".
The incrementing occurs after x is called, so x still equals 7. ++x would equal 8 when x is called
When you re-assign the value for x it is still 7. Try x = ++x and you will get 8 else do
x++; // don't re-assign, just increment
System.out.println(x); // prints 8
because x++ increments the value AFTER assigning it to the variable.
so on and during the execution of this line:
x++;
the varialbe x will still have the original value (7), but using x again on another line, such as
System.out.println(x + "");
will give you 8.
if you want to use an incremented value of x on your assignment statement, use
++x;
This will increment x by 1, THEN assign that value to the variable x.
[Edit]
instead of x = x++, it's just x++; the former assigns the original value of x to itself, so it actually does nothing on that line.
What happens when int x = 7; x = x++;?
ans -> x++ means first use value of x for expression and then increase it by 1.
This is what happens in your case. The value of x on RHS is copied to variable x on LHS and then value of x is increased by 1.
Similarly ++x means -> increase the value of x first by one and then use in expression .
So in your case if you do x = ++x ; // where x = 7
you will get value of 8.
For more clarity try to find out how many printf statement will execute the following code
while(i++ <5)
printf("%d" , ++i); // This might clear your concept upto great extend
++x is pre-increment -> x is incremented before being used
x++ is post-increment -> x is incremented after being used
int x = 7; -> x get 7 value <br>
x = x++; -> x get x value AND only then x is incremented
So this means:
x++ is not equal to x = x+1
because:
int x = 7; x = x++;
x is 7
int x = 7; x = x = x+1;
x is 8
and now it seems a bit strange:
int x = 7; x = x+=1;
x is 8
very compiler dependent!
Most simplest explanation!
This is because ++ after the operand makes post increment it, means first the value got assigned to the variable & then incremented. While if you're expecting x value to be 8 then you should pre increment it like the way mentioned below:
x = x++;
This is the post-increment operator. It should be understood as "Use the operand's value and then increment the operand".
If you want the reverse to happen i.e "Increment the operand and then use the operand's value", you must use the pre-increment operator as shown below.
x = ++x;
This operator first increments the value of x by 1 and then assigns the value back to x.
I think this controversy can be resolved without going into code & just thinking.
Consider i++ & ++i as functions, say Func1 & Func2.
Now i=7;
Func1(i++) returns 7, Func2(++i) returns 8 (everybody knows this). Internally both the functions increment i to 8 , but they return different values.
So i = i++ calls the function Func1. Inside the function i increments to 8, but on completion the function returns 7.
So ultimately 7 gets allocated to i. (So in the end, i = 7)
This is because you used a post-increment operator.
In this following line of code
x = x++;
What happens is that, you're assigning the value of x to x. x++ increments x after the value of x is assigned to x. That is how post-increment operators work. They work after a statement has been executed. So in your code, x is returned first after then it is afterwards incremented.
If you did
x = ++x;
The answer would be 8 because you used the pre-increment operator. This increments the value first before returning the value of x.

Categories