Question

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??

Was it helpful?

Solution

  • 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) );

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top