0

I have following C program and I'm not understanding the output of this program:

#include <stdio.h>

int main()
{
    int a=8;

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

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

    printf("%d\n", a*a);

    return 0;
}

The value of first printf is 8 and the value of second printf is 10!! But how??

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
opu 웃
  • 464
  • 1
  • 7
  • 22

2 Answers2

2
  • a++ is postfix notation, the value is first incremented, but the previous value is returned, which is then passed into prinf.
  • ++a is prefix notation, the value is first incremented before it's passed into printf.

Your code is roughly equivalent to this:

int a = 8;
printf("%d\n", a);
a++;

a++;
printf("%d\n", a);
printf("%d\n", a*a);
return 0;

But it's closer to this (note I'm using the , operator, which evaluates each sub-expression but only returns the final sub-expression):

int a = 8; int aTemp;

// a++
printf("%d\n", (aTemp = a, a = a + 1, aTemp) );

// ++a
printf("%d\n", (a = a + 1) );
Dai
  • 141,631
  • 28
  • 261
  • 374
  • 1
    Actually `a` is incremented *before* the call to `printf` is evaluated. `a++` just evaluates to the old value of `a`, not the new value. – sepp2k Mar 09 '14 at 04:07
  • @sepp2k Yes, I was just rephrasing it to be simpler to understand. – Dai Mar 09 '14 at 04:24
  • @sepp2k I've reworded my answer and provided a better equivalent expression. – Dai Mar 09 '14 at 04:33
  • @Scotia it represents the intermediate value of `a++` that would exist in a CPU register or stack-space during the method-call. – Dai Mar 09 '14 at 04:44
  • How this line `printf("%d\n", (aTemp = a, a = a + 1, aTemp) );` is printing 8??? – opu 웃 Mar 09 '14 at 04:49
  • 1
    @Scotia See here: http://en.wikipedia.org/wiki/Comma_operator – Dai Mar 09 '14 at 04:52
1

a++ will use a in the current statement (in this case output to screen) and then increment "a" after the statement.

++a will increment "a" before the statement is executed.

Russell Jonakin
  • 1,716
  • 17
  • 18