-2

I have been diving deep into understanding the operator precedence in Object oriented programming. Given below is the code:

             int a=5;
             int b=5;
             printf("Output %d",a++>b);
             return 0;

The output is Output 0.

As per my understanding, unary operators has higher precedence over relational operator. So shouldn't a++>b be 6>5. Which is True. But the code outputs False. can anybody explain me why?

Thank you in advance.

1 Answers1

2

You get false because you're using the postfix increment operator when you're doing a++, which in your case results in the comparison 5 > 5.

The postfix increment operator can be thought of in this way. Note: It's illegal code made to demonstrate this only:

class int {                 // if there had been an "int" class
    int operator++(int) {   // postfix increment 
        int copy = *this;   // make a copy of the current value
        *this = *this + 1;  // add one to the int object
        return copy;        // return the OLD value
    }
};

If you had used the prefix increment operator, ++a, you'd gotten the comparison 6 > 5 - and therefor the result true. The prefix increment operator can be thought of in this way. Again, illegal code:

class int {
    int& operator++() {    // prefix increment
        *this = *this + 1; // add one to the int object
        return *this;      // return a reference to the actual object
    }
};
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108