开发者

C-operator precedence confusion

main()
{
  int a=3+2%5;
  printf("%d",a开发者_JS百科);
}

The program returns value 5, but how & why?


Because your arithmetic expression parses as 3+(2%5).

See this table, and note that % is higher precedence than +.


% has higher precedence than + so

3 + 2 % 5

is equivalent to

3 + ( 2 % 5 )

which gives 5.


It's simple, '%' binds more than '+'.

3+2%5

is semantically equivalent to

3+(2%5)

which is obviously 5


Modulus is evaluated at the same precedence as multiplication and division.

2 % 5 = 2
2 + 3 = 5


The mod operator(%) has precedence over the addition operator and hence '2%5' gets calculated first resulting in 2 and then 3 + 2 is calculated resulting in your answer 5.


Because it's interpreted as 3 + (2 % 5). When you divide 2 by 5, the remainder is 2 and adding that to the 3 gives you 5.

The reason it's interpreted that way is in section 6.5.5 of the ISO C99 standard:

multiplicative-expression:
    cast-expression
    multiplicative-expression * cast-expression
    multiplicative-expression / cast-expression
    multiplicative-expression % cast-expression

In other words, % is treated the same as * and / and therefore has a higher operator precedence than + and -.


Your code is equivalent to:

main() { 
    int a = 3 + (2 % 5); 
    printf("%d",a); 
}

See operator precedence table.

2 % 5 (=2) is evaluated first, followed by 3 + 2, hence the answer 5

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜