-1

I wrote this text code

int b=5;
int main()
{
    b=b++;
    printf("b = %d\n",b);
    return 0;
}

and I expected it to print "b = 6"; however, the result is "b = 5", i.e. b is not incremented. I know b=b++ is not a good practice but just to understand it, can anyone explain why it is not incrementing b please? What am I missing?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Guille
  • 326
  • 2
  • 10
  • this is undefined behavior, on my compiler I get b = 6. Your compiler might say 6 tomorrow – pm100 Mar 01 '22 at 00:53

1 Answers1

1

b++ means incrementing the value after it is used so for your case it should be ++b. When b is incrementing to 6 by b++ it is overwritten by assignment of b when it is 5.

Just write it

int b=5;
int main()
{
    // b=b++;
    b++;
    // or ++b;
    printf("b = %d\n",b);
    return 0;
}
David Yappeter
  • 1,434
  • 3
  • 15
  • Ok, I knew that b++ was the right one, but I just was curious to understand why b=b++ fails (yet not yielding an error) and your post perfectly answers that. Many thanks! – Guille Feb 06 '22 at 10:31
  • 1
    "_When b is incrementing to 6 by b++ it is overwritten by assignment of b when it is 5._": OP's code has undefined behavior because the two side-effects on `b` are unsequenced. – user17732522 Feb 14 '22 at 06:32
  • I am not sure who and how judge that "this question does not show any research effort, it is unclear or not useful", nevertheless I do think that non of these are true: I can guarantee I spent time trying to find the answer by myself. It has also have to be considered that one of the fundamental reasons for the existence of the forum is to share knowledge in a direct and quick way. Of course if I had study for hours reading hundreds of pages and books I would have found the answer by myself. But in that case there would be no reason for the existence of Stackoverflow, would it? – Guille Feb 15 '22 at 14:36
  • how on earth does this get so many upvotes when it's completely wrong and is actually UB? – phuclv Mar 01 '22 at 02:33
  • @phuclv UB? Would be appropriate to be a little less cryptic in the forum (also considering that perhaps the majority of users are not English mother tongue... – Guille Mar 02 '22 at 08:17
  • UB = undefined behavior which is what you'll know when you read the duplicate question and you'll see it everywhere once you master C and read stackoverflow a lot – phuclv Mar 02 '22 at 09:26