aspose file tools*
The moose likes C / C++ and the fly likes Resovle This expression(C) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Languages » C / C++
Bookmark "Resovle This expression(C)" Watch "Resovle This expression(C)" New topic
Author

Resovle This expression(C)

Arjun Srivastava
Ranch Hand

Joined: Jun 23, 2010
Posts: 432

x=4+2%-8;
This gives output=6
Please anyone explain how?


SCJP 6 | FB : Java Certifications-Help. | India Against Corruption
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40029
    
  28
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

    Joined: Oct 13, 2005
    Posts: 40029
        
      28
    You're not going to believe this, but the following Java™ code prints 6
    Arjun Srivastava
    Ranch Hand

    Joined: Jun 23, 2010
    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
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40029
        
      28
    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
     
    subject: Resovle This expression(C)