Using the comma operator

Operators will be covered later in this chapter; however, it is useful to introduce the comma operator here. You can have a sequence of expressions separated by a comma as a single statement. For example, the following code is legal in C++:

    int a = 9;    int b = 4;    int c;    c = a + 8, b + 1;

The writer intended to type c = a + 8 / b + 1; and : they pressed comma instead of a /. The intention was for c to be assigned to 9 + 2 + 1, or 12. This code will compile and run, and the variable c will be assigned with a value of 17 (a + 8). The reason is that the comma separates the right-hand side of the assignment into two expressions, a + 8 and b + 1, and it uses the value of the first expression to assign c. Later in this ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.