In the
C and
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming languages, the comma operator (represented by the
token ,
) is a
binary operator
In mathematics, a binary operation or dyadic operation is a rule for combining two elements (called operands) to produce another element. More formally, a binary operation is an operation of arity two.
More specifically, an internal binary o ...
that evaluates its first
operand
In mathematics, an operand is the object of a mathematical operation, i.e., it is the object or quantity that is operated on.
Example
The following arithmetic expression shows an example of operators and operands:
:3 + 6 = 9
In the above exam ...
and discards the result, and then evaluates the second operand and returns this value (and type); there is a
sequence point A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are ...
between these evaluations.
The use of the comma token as an is distinct from its use in
function call
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
s and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a .
The comma operator has been
deprecated
In several fields, especially computing, deprecation is the discouragement of use of some terminology, feature, design, or practice, typically because it has been superseded or is no longer considered efficient or safe, without completely removing ...
in subscripting expressions (as of
C++20 C20 or C-20 may refer to:
Science and technology
* Carbon-20 (C-20 or 20C), an isotope of carbon
* C20, the smallest possible fullerene (a carbon molecule)
* C20 (engineering), a mix of concrete that has a compressive strength of 20 newtons per sq ...
); to make for better use of that syntax, for use as is available in other languages.
Syntax
The comma operator separates ''expressions'' (which have value) in a way analogous to how the
semicolon
The semicolon or semi-colon is a symbol commonly used as orthographic punctuation. In the English language, a semicolon is most commonly used to link (in a single sentence) two independent clauses that are closely related in thought. When a ...
terminates ''statements,'' and sequences of expressions are enclosed in parentheses analogously to how sequences of statements are enclosed in braces:
(a, b, c)
is a sequence of expressions, separated by commas, which evaluates to the last expression
c
, while
is a sequence of statements, and does not evaluate to any value. A comma can only occur between two expressions – commas ''separate'' expressions – unlike the semicolon, which occurs at the end of a (non-block) statement – semicolons ''terminate'' statements.
The comma operator has the lowest
precedence of any C operator, and acts as a
sequence point A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are ...
. In a combination of commas and semicolons, semicolons have lower precedence than commas, as semicolons separate statements but commas occur within statements, which accords with their use as ordinary punctuation:
a, b; c, d
is grouped as
(a, b); (c, d)
because these are two separate statements.
Examples
In this example, the differing behavior between the second and third lines is due to the comma operator having lower precedence than assignment. The last example differs as well since the return expression must be fully evaluated before the function can return.
/**
* Commas act as separators in this line, not as an operator.
* Results: a=1, b=2, c=3, i=0
*/
int a=1, b=2, c=3, i=0;
/**
* Assigns value of b into i.
* Commas act as separators in the first line and as an operator in the second line.
* Results: a=1, b=2, c=3, i=2
*/
int a=1, b=2, c=3;
int i = (a, b);
/**
* Assigns value of a into i.
* Equivalent to: int i = a; int b;
* Commas act as separators in both lines.
* The braces on the second line avoid variable redeclaration in the same block,
* which would cause a compilation error.
* The second b declared is given no initial value.
* Results: a=1, b=2, c=3, i=1
*/
int a=1, b=2, c=3;
/**
* Increases value of a by 2, then assigns value of resulting operation a + b into i.
* Commas act as separators in the first line and as an operator in the second line.
* Results: a=3, b=2, c=3, i=5
*/
int a=1, b=2, c=3;
int i = (a += 2, a + b);
/**
* Increases value of a by 2, then stores value of a to i, and discards unused
* values of resulting operation a + b.
* Equivalent to: (i = (a += 2)), a + b;
* Commas act as separators in the first line and as an operator in the third line.
* Results: a=3, b=2, c=3, i=3
*/
int a=1, b=2, c=3;
int i;
i = a += 2, a + b;
/**
* Assigns value of a into i.
* Commas act as separators in both lines.
* The braces on the second line avoid variable redeclaration in the same block,
* which would cause a compilation error.
* The second b and c declared are given no initial value.
* Results: a=1, b=2, c=3, i=1
*/
int a=1, b=2, c=3;
/**
* Commas act as separators in the first line and as an operator in the second line.
* Assigns value of c into i, discarding the unused a and b values.
* Results: a=1, b=2, c=3, i=3
*/
int a=1, b=2, c=3;
int i = (a, b, c);
/**
* Returns 6, not 4, since comma operator sequence points following the keyword
* return are considered a single expression evaluating to rvalue of final
* subexpression c=6.
* Commas act as operators in this line.
*/
return a=4, b=5, c=6;
/**
* Returns 3, not 1, for same reason as previous example.
* Commas act as operators in this line.
*/
return 1, 2, 3;
/**
* Returns 3, not 1, still for same reason as above. This example works as it does
* because return is a keyword, not a function call. Even though compilers will
* allow for the construct return(value), the parentheses are only relative to "value"
* and have no special effect on the return keyword.
* Return simply gets an expression and here the expression is "(1), 2, 3".
* Commas act as operators in this line.
*/
return(1), 2, 3;
Uses
The comma operator has relatively limited use cases. Because it discards its first operand, it is generally only useful where the first operand has desirable
side effects
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
that must be ''sequenced before'' the second operand. Further, because it is rarely used outside of specific idioms, and easily mistaken with other commas or the semicolon, it is potentially confusing and error-prone. Nevertheless, there are certain circumstances where it is commonly used, notably in for loops and in
SFINAE. For embedded systems which may have limited debugging capabilities, the comma operator can be used in combination with a macro to seamlessly override a function call, to insert code just before the function call.
For loops
The most common use is to allow multiple
assignment
Assignment, assign or The Assignment may refer to:
* Homework
* Sex assignment
* The process of sending National Basketball Association players to its development league; see
Computing
* Assignment (computer science), a type of modification to ...
statements without using a block statement, primarily in the initialization and the increment expressions of a
for loop
In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied.
For-loops have two par ...
. This is the only idiomatic use in elementary C programming. In the following example, the order of the loop's initializers is significant:
void rev(char *s, size_t len)
An alternative solution to this problem in other languages is
parallel assignment
In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable. In most imperative programming languages, the assi ...
, which allows multiple assignments to occur within a single statement, and also uses a comma, though with different syntax and semantics. This is used in
Go in its analogous for loop.
Outside of for loop initializers (which have a special use of semicolons), the comma might be used instead of a semicolon, particularly when the statements in question function similarly to a loop increment (e.g. at the end of a while loop):
++p, ++q;
++p; ++q;
Macros
The comma can be used in preprocessor macros to perform multiple operations in the space of a single syntactic expression.
One common use is to provide custom error messages in failed assertions. This is done by passing a parenthesized expression list to the
assert
macro, where the first expression is an error string and the second expression is the condition being asserted. The
assert
macro outputs its argument verbatim on an assertion failure. The following is an example:
#include
#include
int main ( void )
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
assert: assert.c:6: test_assert: Assertion `( "i is too big!", i <= 4 )' failed.
Aborted
However the assert macro is usually disabled in production code, so use it only for debug purposes.
Condition
The comma can be used within a condition (of an if, while, do while, or for) to allow auxiliary computations, particularly calling a function and using the result, with
block scoping
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
:
if (y = f(x), y > x)
A similar idiom exists in
Go, where the syntax of the if statement explicitly allows an optional statement.
Complex return
The comma can be used in return statements, to assign to a global variable or out parameter (passed by reference). This idiom suggests that the assignments are part of the return, rather than auxiliary assignments in a block that terminates with the actual return. For example, in setting a global error number:
if (failure)
return (errno = EINVAL, -1);
This can be written more verbosely as:
if (failure)
Avoid a block
For brevity, the comma can be used to avoid a block and associated braces, as in:
if (x 1) y = 2, z = 3;
if (x 1)
y = 2, z = 3;
instead of:
if (x 1)
if (x 1)
Other languages
In the
OCaml and
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
programming languages, the semicolon (";") is used for this purpose.
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
and
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
utilize the comma operator in the same way C/C++ does. In
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
, the comma is a separator used to separate elements in a list in various contexts.
It is not an operator and does not evaluate to the last element in the list.
See also
*
Sequence point A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are ...
*
Operators in C and C++
This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.
When n ...
*
Operator (programming)
In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.
Common simple examples include arithmetic (e.g. addition with ), c ...
References
Bibliography
*
*
*
{{refend
External links
*
Effect of using a comma instead of a semi-colon in C and C++, ''Stack Overflow''
*
– facility from the
Boost library that makes it easy to fill containers by overloading the comma operator
C (programming language)
C++
Operators (programming)