1
int main()
{
    int a=0;
    a=a++;
    printf ("%d",a);
}

In this question, why does the value of a comes out to be 0 and not 1?

I mean, I understand that due to post-increment, the value assigned to a is 0. But then a++ runs, so why doesn't the value of a becomes 1?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    The real question is *when* does the `++` part run, and more importantly, *is that behaviour defined*. Another way to get to the bottom of "why" is to look at the assembly dump of the compiled output. – tadman Feb 09 '21 at 18:49
  • [Useful documentation on `++`](https://en.cppreference.com/w/c/language/operator_incdec) – user4581301 Feb 09 '21 at 18:53
  • [Useful documentation on what happens when](https://en.cppreference.com/w/c/language/eval_order) and what has no defined behaviour. – user4581301 Feb 09 '21 at 18:55
  • For this to work, you should just use a++, or use pre-increment: a=++a; Your approach is not working because it is storing a (let say, in a temporal variable t), incrementing a, and assigning t as the value of a. As you can see, the incremented value is never stored back into a. – Alberto Casas Ortiz Feb 09 '21 at 18:59
  • *"why does the value of a comes out to be 0 and not 1"* [Well..](https://godbolt.org/z/hYjs49) – Bob__ Feb 09 '21 at 19:06

0 Answers0