• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Resovle This expression(C)

 
Arjun Srivastava
Ranch Hand
Posts: 432
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x=4+2%-8;
This gives output=6
Please anyone explain how?
 
Campbell Ritchie
Sheriff
Pie
Posts: 47313
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Sheriff
    Pie
    Posts: 47313
    52
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You're not going to believe this, but the following Java™ code prints 6
     
    Arjun Srivastava
    Ranch Hand
    Posts: 432
    Eclipse IDE Firefox Browser Java
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
    Sheriff
    Pie
    Posts: 47313
    52
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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.
     
    I agree. Here's the link: http://aspose.com/file-tools
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic