Pointer operations and operator precedence in C

后端 未结 6 814
野性不改
野性不改 2021-02-04 03:32

Background

Just had a chat with a C guy today and we disagreed on the following:

int intgA[2] = { 1, 2 };
int intgB[2] = { 3, 5 };

int *intAPtr = intg         


        
6条回答
  •  既然无缘
    2021-02-04 04:14

    The statement

    *intAPtr++ = *intBPtr++;
    

    is parsed as

    *(intAPtr++) = *(intBPtr++);
    

    and breaks down as follows:

    • The value currently pointed to by intBPtr (3) is assigned to the location pointed to by intAPtr (intgA[0]);
    • The pointers intAPtr and intBPtr are incremented.

    The exact order in which these things happen is unspecified; you cannot rely on intBPtr being incremented after intAPtr or vice-versa, nor can you rely on the assignment occuring before the increments, etc.

    So by the time this is all done, intgA[0] == 3 and intAPtr == &intgA[1] and intBPtr == &intgB[1].

    The expression a++ evaluates to the value of a before the increment.

提交回复
热议问题