简体   繁体   中英

Pre and post increment in programming

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, ie the printf statement.

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

Thank you

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

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.

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

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

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

Hope this makes it clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM