문제

Given the following code:

 int  a=0,b=1;
 int r=a+++b;

which are the operations performed and in which order?

   a++ + b
   a + ++b

I this compiler specific or does it depend on the standard?

도움이 되었습니까?

해결책

It is (a++) + b but not because of operator precedence.

It is parsed as (a++) + b because the compiler takes the longest token it can from a sequence of characters. In other words, the lexer keeps reading characters until it encounters something that can't be part of the same token as what it already has.

This is also how it interprets >= as one token instead of > and =, and double as 'double' not 'do uble'.

There are rules of operator precedence for statements like

a || b && c
// "a || (b && c)" NOT "(a || b) && c", because && takes precedence

However, in your case the operators ++ and + have already been determined. Once the operators have been determined, the rules of operator precedence can apply.

There are some good answers to Why doesn't a+++++b work in C? that should explain this in more detail.

다른 팁

That is governed by the operator precedence. Since postfix ++ has a higher precedence than the + operator it binds tighter to a is post incremented then added to b so the result is:

(a++) + b
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top