1

I am learning C language and now I am confused with the output of the below snippet.

#include <stdio.h>

int main(void) {
    int p = 20;
    printf("%d\n",++p + p++);
    return 0;
}

Online Fiddle

How is the output of this 43?

As far as I have understood, it should be evaluating as below:

  • ++p makes it 21.
  • p++, makes it 22 but will be 21 during addition since it is post-increment.

So the expected output should be 21 + 21 = 42. Isn't it?

varun_2799
  • 19
  • 2
  • 1
    There is one point you have not understood, and that is: when there are too many things going on in a single expression — in this case, when there are two separate attempts to update the value of `p` — everything falls apart. There is no rule to say which happens first, so anything can happen. (And in particular, there is no rule that says things happen left-to-right, or anything like that.) – Steve Summit Jan 01 '23 at 16:49
  • 1
    Evaluating this code at tio.run you'll find that the clang and tcc compilers produce 42, while GCC produces 43. – Bob Jarvis - Слава Україні Jan 01 '23 at 16:51
  • Giga-dupe, covered by the FAQ:( – Martin James Jan 01 '23 at 22:31

0 Answers0