The benefit of the comma operator is that it allows you to include a sub-expression for its side-effects only. In languages without a comma operator, there are often ways around this ─ suppose
f is an expression you want to evaluate just for its side-effects, and then
g is the expression whose value you actually want:
- In languages with list or tuple literals, you can write
- In languages with dynamically-typed logical operators, you can write
(f || true) && g.
- In languages with
in expressions, you can write
let _ = f in g.
- In most cases, you can define a function like
comma(f, g) which just returns
in expressions like
Also, including the comma operator like this may mean less syntax space is available for other things. For example, in Python,
(f, g) or
f, g are expressions which create a tuple, so they can't also mean something else.
The comma operator would also be almost entirely superfluous in languages where expressions cannot have side-effects, such as pure functional languages ─ the first operand would only matter if it was eagerly evaluated but diverged. (Haskell's
seq behaves like this, and is considered harmful by some.)