c++ccoding-stylecomma-operator

What is the proper use of the comma operator?


I saw this code:

if (cond) {
    perror("an error occurred"), exit(1);
}

Why would you do that? Why not just:

if (cond) {
    perror("an error occurred");
    exit(1);
}

Solution

  • In your example it serves no reason at all. It is on occasion useful when written as

    if(cond)
      perror("an error occured"), exit(1) ;
    

    -- then you don't need curly braces. But it's an invitation to disaster.

    The comma operator is to put two or more expressions in a position where the reference only allows one. In your case, there is no need to use it; in other cases, such as in a while loop, it may be useful:

    while (a = b, c < d)
      ...
    

    where the actual "evaluation" of the while loop is governed solely on the last expression.