This is because a++ is post incremented that is first the value of a is assigned to a and the incremented value is being lost.incidentally, writing a=a++ is very poor coding style, for obvious reasons, and is to be avoided in all situations. This might have something to do with memory management in C.I am trying to explain it using a stack.Stack is used in recursion to store the values and it must be something like that here too.But i am not getting any reliable sources.From recursion i understand this principle is right.
A compiled C program creates and uses four logically distinct regions of memory. The first region is
the memory that actually holds the program's executable code. The next region is memory where
global variables are stored. The remaining two regions are the stack and the heap.
"The stack is used for a great many things while your program executes. It holds the return addresses of function calls,arguments to functions, and local variables. It will also save the current state of the CPU. The heap is a region of free memory that your program can use via C's dynamic memory allocation functions"
The important thing to think about in this case is how such expressions are evaluated and how they are executed. The rules are:
1. If the ++ appears BEFORE the variable, the variable's value is incremented FIRST. THEN, the variable's value is resolved.
2. If the ++ appears AFTER the variable, the variable's value is resolved FIRST. THEN, the variable's value is incremented.
OK. Those are the rules. Now an example. I think I'll use a fuller example to explain how this works so you can get into the rhythm of how such expressions are evaluated and executed.
1: int a = 2;
2: a= a++;
3:printf("%d",a); // 2
On line 2, a++ examined. Using rule (2) from above, the variable's value is first resolved, in this case, to 2.This value is pushed into the stack.
Then variable 'a' is then incremented from 2 to 3 by a++. Thus 3 is pushed into stack.
This effectively leaves the program stack as::-
[3]
[2]
Now stack follows the principle of LIFO(Last in first out).So variable a is now assigned values from stack by pop operation.First it is assigned 3 then 2.
...and this is the important point. Although the variable 'i' currently contains 3, that value will be overwritten when the above line of code executes, overwriting the 3, with a 2.
a=a++; //here a is assigned value 2 and that is what is retained
#include
#include
int main(void)
{
int b,a=2;
b=a++; //b is assigned 2 then a is incremented to 3 ::here we have to variables so popped values goes to different addresses
printf("%d",b);
printf("%d",a);
return 0;
}