void.pointer
void.pointer

Reputation: 26415

ternary and assignment operator precedence

On MSVC v9.0, if I do this:

int myvalue;
myvalue = true ? 1 : 0;

then it seems that ?: is evaluated before '='. Is this a guarantee? I am using this table as a reference: http://en.cppreference.com/w/cpp/language/operator_precedence

However, both operators are in the same row, so I'm not sure if they are evaluated in the order I expect or if this is guaranteed by the standard. Can anyone clarify this?

Upvotes: 1

Views: 217

Answers (4)

Bob Fincheimer
Bob Fincheimer

Reputation: 18076

Right-to-left:

int myValue1 = 20, myValue2 = 30;

myValue1 = true ? 1 : 0; // which is the same as:
myValue1 = ((true) ? (1) : (0));

// myValue == 1 && myValue2 == 30

true ? myValue1 : myValue2 = 5; // which is the same as:
(true) ? (myValue1) : ((myValue2) = (5));

// myValue == 1 && myValue2 == 30

false ? myValue1 : myValue2 = 5; // which is the same as:
(false) ? (myValue1) : ((myValue2) = (5));

// myValue == 1 && myValue2 == 5

This is guaranteed in the C++ language

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308520

From your link:

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. For example, the expression a=b=c is parsed as a=(b=c), and not as (a=b)=c because of right-to-left associativity.

Since both = and ?: are in the same cell and have right-to-left associativity, the ternary is guaranteed to evaluate first.

Upvotes: 3

Kos
Kos

Reputation: 72319

In this statement

int myvalue = true ? 1 : 0;

there's only one operator, the ternary operator. There's no assignment operator here, so precedence doesn't matter.

Don't confuse initialization with assignment:

int myvalue;
myvalue = true ? 1 : 0; // now priorities are important

Upvotes: 7

Matzi
Matzi

Reputation: 13925

They are evaluated right to left, as it written in the table you linked. It is equivalent of this:

int myvalue = (true ? 1 : 0);

Upvotes: 0

Related Questions