Pointer operations and operator precedence in C

后端 未结 6 813
野性不改
野性不改 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:16

    Yes, ++ binds tighter than *, but you have misunderstood how it works. var++ increments var, but it evaluates to the value of var before the increment. You can think of it as syntactic sugar for (var += 1, var - 1) if you like.

    Another way to think about this is: if it worked the way you thought it did, then there would be no difference between var++ and ++var, and one of them would not have been included in the language in the first place. C has almost no redundancies.

    (The binding precedence does matter; for instance, it means *var++ increments the value of the variable var whereas (*var)++ increments the value in the memory location at *var.)

提交回复
热议问题