Search code examples
ccomma-operator

Does the comma operator make the code slower?


I use the comma operator (in C) very often when solving problems on websites like CodeForces. and I've been noticing that my solutions seem to need more execution time than most of the other solutions, although there isn't much difference.

So my question is does the comma operator put more overhead on the CPU? like if the evaluation of its two operands isn't necessary. Would it be faster to separate them in two statements? Or the compiler would optimize it anyway?


Solution

  • No. The comma operator does not make code slower.

    With that said, though, the comma operator is rare in most code. Pretty much the only time you need it is when you're running a for loop over two variables, as in

    for(i = 0, j = n; i < j; i++, j--)
    

    (I believe there are C-like languages that permit the comma operator only in the first and third expressions of a for loop, disallowing it everywhere else.)

    Any other time you're using a comma operator, it usually indicates you're doing something "clever" but unnecessary, which mainly serves to make your code more confusing or harder to read.

    (With that said, though, it's also true that most of the commas in most C programs are not comma operators. The commas separating the arguments in function calls are not comma operators, nor are the commas separating multiple declarations like int i, j;.)