ProgrammingC Developer, System Programmer

Explain how the comma operator works in the C language. When does it make sense to use it, what common mistakes do developers encounter when using it, and what unexpected effects can arise?

Pass interviews with Hintsage AI assistant

Answer

The comma operator , in C combines two (or more) expressions, evaluating them in order from left to right and returning the value of the last expression:

int x = (f(), g()); // f() and g() are called, x == result of g()

It is most commonly used in for loops:

for(int i = 0, j = 10; i < j; ++i, --j) { ... }

When useful:

  • When you need to concisely write several expressions, especially in initialization or increment.

Pitfalls:

  • The precedence of the comma is very low, which is important in complex expressions;
  • Using it out of context (e.g., in return or assignment) can lead to unexpected results;
  • Using it without parentheses can confuse both the programmer and the compiler.

Trick question

Question: What will the following code print?

int a = 1; int b = (a = 2, a + 3); printf("%d ", b);

Answer: It will print "5". First, a=2 is assigned, after which the expression a+3 evaluates to 2+3=5, and this value is assigned to variable b.


Examples of real errors


Story

In a C project, a developer used the comma operator without parentheses in a return function:

return x++, y++;

It was expected that the function would return y+1, but actually return only considers the result of the expression on the right, while on the left x++ is evaluated separately. This confused the user's code, as the return result was not what was intended.


Story

In one for loop, the programmer accidentally placed a comma instead of a semicolon:

for(i=0, i<10, i++) ...

The program compiled, but the loop executed only once, as the expression i<10, i++ in the for conditions always returns the value of the last expression (i++), not the loop continuation condition.


Story

When writing macros, one developer defined:

#define DO(x, y) x, y int v = DO(f(), g());

Expected both functions to be called, but forgot to put parentheses. As a result, only f() was called; the value of g() was not assigned to v. Correct usage: #define DO(x, y) ((x), (y)).