This question already has an answer here:
- What does the comma operator , do? 8 answers
You see it used in for loop statements, but it's legal syntax anywhere. What uses have you found for it elsewhere, if any?
This question already has an answer here:
You see it used in for loop statements, but it's legal syntax anywhere. What uses have you found for it elsewhere, if any?
I often use it to run a static initializer function in some cpp files, to avoid lazy initalization problems with classic singletons:
For me the one really useful case with commas in C is using them to perform something conditionally.
this is equivalent to
This is not about "typing less", it's just looks very clear sometimes.
Also loops are just like that:
Of course both can only be useful when the conditional part or executable part of the loop is quite small, two-three operations.
From the C standard:
In short it let you specify more than one expression where C expects only one. But in practice it's mostly used in for loops.
Note that:
is NOT the comma operator, it's a list of declarators.
I had to use a comma to debug mutex locks to put a message before the lock starts to wait.
I could not but the log message in the body of the derived lock constructor, so I had to put it in the arguments of the base class constructor using : baseclass( ( log( "message" ) , actual_arg )) in the initialization list. Note the extra parenthesis.
Here is an extract of the classes :
In general I avoid using the comma operator because it just makes code less readable. In almost all cases, it would be simpler and clearer to just make two statements. Like:
offers no clear advantage over:
The one place besides loops where I have used it it in if/else constructs, like:
You could put the function before the IF, but if the function takes a long time to run, you might want to avoid doing it if it's not necessary, and if the function should not be done unless a!=1, then that's not an option. The alternative is to nest the IF's an extra layer. That's actually what I usually do because the above code is a little cryptic. But I've done it the comma way now and then because nesting is also cryptic.
qemu has some code that uses the comma operator within the conditional portion of a for loop (see QTAILQ_FOREACH_SAFE in qemu-queue.h). What they did boils down to the following:
... with the following output:
The first version of this loop has the following effects:
&&
, the assignment is not evaluated after the last iteration