Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 361
Kam Avatar asked Jul 27 '13 22:07

Kam


2 Answers

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.

like image 124
Jongware Avatar answered Sep 21 '22 19:09

Jongware


Legitimate cases of the comma operator are rare, but they do exist. One example is when you want to have something happen inside of a conditional evaluation. For instance:

std::wstring example; auto it = example.begin(); while (it = std::find(it, example.end(), L'\\'), it != example.end()) {     // Do something to each backslash in `example` } 

It can also be used in places where you can only place a single expression, but want two things to happen. For instance, the following loop increments x and decrements y in the for loop's third component:

int x = 0; int y = some_number; for(; x < y; ++x, --y) {     // Do something which uses a converging x and y } 

Don't go looking for uses of it, but if it is appropriate, don't be afraid to use it, and don't be thrown for a loop if you see someone else using it. If you have two things which have no reason not to be separate statements, make them separate statements instead of using the comma operator.

like image 43
Billy ONeal Avatar answered Sep 21 '22 19:09

Billy ONeal