Pre and post increment in programming

So, I played in increments of C, and I ran this code

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

}

Initially, I thought, oh yes, it’s easy ... Therefore, I thought that it would print 3 and 3.

This is due to the fact that ++ is an increment by mail and increases the value after it has been used in this function. Answer instead

a=4
b=3

I do not understand how post increment a is added before the function completes, i.e. printf instructions.

Can someone explain why the answer is what it is.

thank

+1
source share
4 answers

Post-increment is a post (after) its use, and not after printf(). It has changed before you reach your challenge printf().

+4
source

, :

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

printf . ,

b = a++;

,

b = postincremnt(&a);

.

+3

, a b, a 1. b=++a;, a = 4, b = 4

+1

b = a++;, b = a; a = a + 1;.

b = ++a;, a = a + 1; b = a;

, .

0

All Articles