1
votes

So I was playing around with increments in C and I ran this code

int main() {
   int a = 3;
   int b = 8;
   b = a++;
   printf("%d %d",a, b);
return 1;

}

Originally I thought, oh yeah that's easy... So I thought it would print out 3 and 3.

This is because a++ is a post increment, and increments the value after it has been used it the function. Instead the answer is

a=4
b=3

I don't understand how post increment a is adding to a before the function has completed, i.e the printf statement.

Can someone explain why the answer is, what it is.

Thank you

4

4 Answers

4
votes

The post increment is post (after) its use, not after the printf(). It's changed before you reach your printf() call.

3
votes

Imagine postincrement as this function:

int postincrement(int* value)
{
    int priorvalue = *value;
    *value = *value + 1;
    return priorvalue; 
}

So printf has nothing to do with your increment. Instead, when you write

b = a++;

Imagine that

b = postincremnt(&a);

was called, which is perfectly consistent with your results.

1
votes

The post increment means that first you asign the current value of a to b and then it increases a by 1. If you had done b=++a; then you would get a=4 , b=4

0
votes

When you did b = a++; it works out as b = a; a = a + 1;.

If you did b = ++a; then it works as a = a + 1; b = a;

Hope this makes it clear.