Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

#include <stdio.h>

int main(void)
{
    int i;
    int *p = (int *) malloc(5 * sizeof(int));

    for (i=0; i<10; i++)
        *(p + i) = i;

    printf("%d ", *p++);
    return 0;
}

So, I ran this code. Now I was told here that Why won't the output be 4 in this case? (in accepted answer) that *p++ will increment pointer first and then dereference it. Therefore, in the above code, shouldn't the pointer be incremented first and then de-referenced and hence output should be 1? Instead, output comes out to be 0. Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
213 views
Welcome To Ask or Share your Answers For Others

1 Answer

You got the precedence part right, but let's see about the postfix increment operator property, shall we?

C11 standard says in chapter §6.5.2.4, Postfix increment and decrement operators

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [...]

So, the variable itself will experience the effect of the increment, but the statement, in which the variable is present(with the postfix increment) will avail the existing value of the variable, not the incremented value. The increment, will be executed as a side-effect at a later part.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...