According to this precedence table, the comma operator is left-associative. That is, a, b, c
is parsed as (a, b), c
. Is that a necessity? Wouldn't a, (b, c)
have the exact same behavior?
Does the comma operator have to be left-associative?
Asked Answered
Since overloadable operator,
exists, no, it's not the same behavior. a, (b, c)
could call different overloads than (a, b), c
.
The comma operator has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.
Commas can be used as separators in some contexts, such as function argument lists. Do not confuse the use of the comma as a separator with its use as an operator; the two uses are completely different.
© 2022 - 2024 — McMap. All rights reserved.
a
,b
andc
are of different types, and each overloads,
which returns a type which overloads,
too?(a,b),c
would not be same asa,(b,c)
. – Exciseman2+3
has same answer for all. – Exciseman(a + b) + c
anda + (b + c)
are guaranteed to be equivalent. (They aren't in floating-point arithmetic for accuracy reasons, and in some exotic number systems they aren't even supposed to). – Perdu(a * b) * c
anda * (b * c)
for octonions, of course) – Perdu+
as well. – Exciseman(a, b), c
anda, (b, c)
will evaluatea
,b
andc
(in that order) and yield the result ofc
. How is that not equivalent? – Broadway(a + b) + c
anda + (b + c)
are also not the same for signed integers in C++. For exampleINT_MAX + (1 + -1)
isINT_MAX
, but(INT_MAX + 1) + -1
invokes undefined behavior due to signed integer overflow. – Broadway(a, b, c);
would evaluate b then c then a. – Khalsa(printf("a"), printf("b")), printf("c");
andprintf("a"), (printf("b"), printf("c"));
both print"abc"
. – Broadway