Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use the comma operator?

Tags:

c++

c

operators

I've recently (only on SO actually) run into uses of the C/C++ comma operator. From what I can tell, it creates a sequence point on the line between the left and right hand side operators so that you have a predictable (defined) order of evaluation.

I'm a little confused about why this would be provided in the language as it seems like a patch that can be applied to code that shouldn't work in the first place. I find it hard to imagine a place it could be used that wasn't overly complex (and in need of refactoring).

Can someone explain the purpose of this language feature and where it may be used in real code (within reason), if ever?

like image 880
John Humphreys Avatar asked Nov 21 '11 23:11

John Humphreys


2 Answers

It can be useful in the condition of while() loops:

while (update_thing(&foo), foo != 0) {
    /* ... */
}

This avoids having to duplicate the update_thing() line while still maintaining the exit condition within the while() controlling expression, where you expect to find it. It also plays nicely with continue;.

It's also useful in writing complex macros that evaluate to a value.

like image 185
caf Avatar answered Sep 29 '22 13:09

caf


Within for loop constructs it can make sense. Though I generally find them harder to read in this instance.

It's also really handy for angering your coworkers and people on SO.

bool guess() {
  return true, false;
}
like image 43
Tom Kerr Avatar answered Sep 29 '22 13:09

Tom Kerr