문제

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

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top