BioExtract
BioExtract

Reputation: 89

Which operator is used first?

I have just taken a test in my c++ class and one of the questions I had gotten wrong is this:

Look at the following statement. while (x++ < 10) Which operator is used first?

My answer was ++ however, the test tells me it is actually <. Could somebody explain why this is?

Upvotes: 1

Views: 9247

Answers (4)

Madhu Kumar Dadi
Madhu Kumar Dadi

Reputation: 735

This is the priority order.

1  Parenthesis                    () []
2  Structure Access               .  ->
3  Unary                          ! ++ -- * &
4  Multiply,Divide,Modulus        * / %
5  Add,Subtract                   + -
6  Shift Right,Left               >> <<
7  Greater,Less than etc          > < => <=
8  Equal , Not Equal              ==  !=
9  Bitwise AND                    &
10 Bitwise OR                     |
11 Logical AND                    &&
12 Logical OR                     ||
13 Conditional Expression         ? :
14 Assignment                     = += -= etc
15 comma                          . 

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172914

You're right. operator++ has a higher precedence over operator<.

C++ Operator Precedence

So, in this case, operator++ will be called first, and then return the original value (before increment), which will be used for the comparasion.

LIVE

Upvotes: 4

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145259

When x is of a type with user defined postfix operator++ then the ++ is necessarily evaluated first.

For x of built-in type I'm not sure if anything can be said about the ordering.

Upvotes: 2

Nick Gammon
Nick Gammon

Reputation: 1171

I suspect this is because x++ is a post-increment. So you could say that it first compared x to 10, and then afterwards added one to x.

Had it been ++x then the add would have been done first.

I think it is a bit of a trick question, because in terms of operator precedence, ++ is higher in precedence than <.

Upvotes: 2

Related Questions