John
John

Reputation: 151

Explain how C evaluates this expression

x=4+2%-8;

This gives output=6 Please anyone explain how?

Upvotes: 2

Views: 14766

Answers (4)

Nobeul Islam
Nobeul Islam

Reputation: 1

Because you can not divide the number 2 by 8. so no division and the number itself(2) will be the output as for the modulus value.

Upvotes: 0

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

If you check this precedence chart first mod is taken and then added to 4

so (2%-8) gives 2
then 2+4 = 6

Upvotes: 7

user418748
user418748

Reputation:

x=4+2%-8; is equivalent to x = 4 + (2 % -8); which gives x = 4 + 2 which is 6.

More: C Operator Precedence Table

Upvotes: 13

Daniela
Daniela

Reputation: 31

Because the precedence of the operator % is the highest from the equation, the program first executes the operation 2 % 8 which is 2 and the adds this to 4.

Upvotes: 3

Related Questions