开发者

why does *ptr++ act like *(ptr++) and not (*ptr)++? [duplicate]

开发者 https://www.devze.com 2023-03-11 13:11 出处:网络
This qu开发者_StackOverflow社区estion already has answers here: Closed 11 years ago. Possible Duplicate:
This qu开发者_StackOverflow社区estion already has answers here: Closed 11 years ago.

Possible Duplicate:

++ on a dereferenced pointer in C?

Similarly, what would *ptr += 1 *ptr % 8, and *ptr / 8 be?

The differences seem confusing. Is this, perhaps, compiler dependent?


It has to do with operator precedence. The * operator has a lower precedence than ++ so it occurs last.

Here's a Wikipedia chart that lists all the operators: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

You can see in the chart that postfix ++ has a precedence of 2 while * dereference has a precedence of 3. (The numbers are slightly backwards, as lower numbers have higher precedence).


Operator precedence. The ++ operator "binds more tightly" than the * operator.

Here's the table, in order of precedence. http://isthe.com/chongo/tech/comp/c/c-precedence.html

This is not compiler dependent. It will always behave this way.


Because of precedence (that's just how C works).

C FAQ on the * exact * subject

The postfix ++ and -- operators essentially have higher precedence than the prefix unary operators. Therefore, *p++ is equivalent to *(p++);


because of operator precedence

the postfix ++ has a higher precedence than the * operator. It's not compiler dependent.

*ptr += 1 will increase the value pointed to by ptr by one (or call the appropriate overloaded operator) *ptr % 8 will calculate the remainder of the value pointed to by ptr divided by 8 *ptr / 8 will calculate the division of the value pointed to by ptr and 8


From wikipedia:

For the ISO C 1999 standard, section 6.5.6 note 71 states that the C grammar provided by the specification defines the precedence of the C operators

This means that the operator precedence is governed by C standard.


The differences seem confusing. Is this, perhaps, compiler dependent?

No, the precedence of operators is defined in the c lang spec. And and so *prt++ is always deferencing the pointer before the post-increment occurs.

0

精彩评论

暂无评论...
验证码 换一张
取 消