Skip to content

Instantly share code, notes, and snippets.

@Micrified
Created February 6, 2024 08:12
Show Gist options
  • Save Micrified/13d8afb2da5bd8d7e7d21cd0a007d30d to your computer and use it in GitHub Desktop.
Save Micrified/13d8afb2da5bd8d7e7d21cd0a007d30d to your computer and use it in GitHub Desktop.
Comma operator in C if-statements

Comma Operator

In C and C++, the comma operator is a binary operator that:

  1. Evaluates the first operand, and discards the result
  2. Evalutes the second operand, and returns this value

So:

if (a,b) {
}

Here, a is evaluated first and then discarded. Next, b is evaluated and returned to the condition. If there are more than two operands, then the last expression will be returned.

Remember this doesn't ensure both conditions are true. For that, you need &&

Uses

The comma operator is handy when you don't need the results (side effect) of a particular operation. For example:

if (numeric_read(str, &err), !err) {
    // Handle ... 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment