简体   繁体   中英

C-operator precedence confusion

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

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 .

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

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

3+2%5

is semantically equivalent to

3+(2%5)

which is obviously 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 - .

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

2 % 5 = 2
2 + 3 = 5

mod运算符(%)的优先级高于加法运算符,因此首先计算“ 2%5”,结果为2,然后计算3 + 2,得出答案5。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM