0

when running the below code the output is 21

#include<stdio.h>
int main()
{int a=10,b=10;

printf("%d",a+(a++));

}

whereas running below code gives output 20

int main()
{int a=10,b=10;

printf("%d",b+(a++));

}

how is 1st code working to get 21 while when same value is assigned to b the post increment operator doesn't work?? (10+10++) in case of a it will work as 10+10=20 then ads 1 and shows the value where as in case of b it will only do 10+10=20 and shows the value. why? is it showing this?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Noobcoder
  • 31
  • 7
  • 3
    In C++ (not sure about C) your first code has *undefined behaviour*, the output could have been anything. It is forbidden to modify a variable and reference it in the same expression. That is a big simplification of the rules, see the duplicate for more details. Because your second code uses two separate variables the behaviour is well-defined. – john Apr 22 '23 at 15:27
  • Your title suggests that you think the output of `20` from your second program is incorrect. That is not true, maybe you need to revise how the post-increment operator works, as well as learning about undefined behaviour. – john Apr 22 '23 at 15:34
  • `printf("%d",a+(a++));` Please don't write code like that - it will cause you a world of grief. – Paul Sanders Apr 22 '23 at 15:46
  • The code `b+(a++)` is well-defined and makes sense. We take `b` and add `a`'s old value, and as a side effect we also increment `a`. But the similar-looking expression `a+(a++)` is, in C anyway, *un*defined and makes no sense. Since we're incrementing `a` as a side effect in the process of evaluating the expression, there's an ambiguity: does the `a` on the left-hand-side of the `+` operator (that is, where `b` used to be) use the old or the new value of `a`? There's no rule to tell us. (And left-to-right evaluation is *not* guaranteed.) – Steve Summit Apr 22 '23 at 16:12

0 Answers0