thrower
thrower

Reputation: 91

What does (expr1, expr2) do on the right side of an assignment?

I recently looked at my old code and I can't figure out what this does, or whether it is valid. The code is something like:

map<string, string> map;
map[string1] = ("s", string2);

Upvotes: 8

Views: 589

Answers (4)

IInspectable
IInspectable

Reputation: 51464

The expression "s", string2 uses the built-in1 comma operator. It has the following semantics:

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded, and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing) (until C++17).

The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand, E2.

In case of your code snippet, it isn't useful at all, and its only purpose is to confuse readers. Since evaluating "s" has no side-effects, the code is identical to this:

map<string, string> map;
map[string1] = string2;


1 This is assuming that no user-defined operator, matching the arguments has been defined. If there is, it can do anything, and the remainder of this answer does not apply. You'd have to look into the source code to find out, what the expression evaluates to.

Upvotes: 6

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275660

This is probably the comma operator, which evaluates everything then discards everything except the right hand side value.

But, if operator,( char const*, string2 ) is overloaded it could do anything (where string2 is the type of string2).

Look for such overloads.

Note that if string2 is a std::string such overloads may make your program ill formed, no diagostic required. Won't stop people from doing it. And it may "work" and still permit , to (for example) cause concatination of strings.

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234745

It's an obfuscation. The comma operator evaluates all the arguments from left to right but discards all arguments apart from the final one. The formal type of the entire expression is the type of the final argument.

(Note also that the comma itself is a sequencing point.)

string2 becomes the value in the map, under key string1.

Upvotes: 13

xinaiz
xinaiz

Reputation: 7788

Comma is operator, that evaluates arguments from left to right, and has value of most-right element.

For example:

int a=2, b=3, c;
c = (a+=b, a*b); 

So, from left, a+=b is evaulated first, which sets a to 2+3, then a*b is evaulated, and expression has value of 5*3, which value is used. So c is 15

Upvotes: 1

Related Questions