Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Resovle This expression(C)

Arjun Srivastava
Ranch Hand
Posts: 432
x=4+2%-8;
This gives output=6

Campbell Ritchie
Marshal
Posts: 55732
163
You have four operators in that expression. They have different precedences
• = Lowest Precedence
• + Higher than = and lower than %
• % Higher than + and lower than -
• - This is here a unary operator, and unary prefix operators have higher precedence than the others in that statement.
• See whether that helps.

Campbell Ritchie
Marshal
Posts: 55732
163
You're not going to believe this, but the following Java™ code prints 6

Arjun Srivastava
Ranch Hand
Posts: 432
Campbell Ritchie wrote:You have four operators in that expression. They have different precedences
• = Lowest Precedence
• + Higher than = and lower than %
• % Higher than + and lower than -
• - This is here a unary operator, and unary prefix operators have higher precedence than the others in that statement.
• See whether that helps.

Yeah,thanks for the reply.I don't know what happens to my maths
But please tell me how 2%-8=2 ?
I know that in C , the sign of result by modulus operator is the sign of numerator.
So that 4+2=6.

Campbell Ritchie
Marshal
Posts: 55732
163
Sorry for the delay in replying.
You have answered your own question. The sign of the result of the remainder operator is the same as the left-hand operand, so 2 % 8 and 2 % (-8) both return 2. I wrote (-8) instead of -8 to remind you of the relative precedences of the operators.