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?
It can be handy for "code golf":
Code Golf: Playing Cubes
The
,
inif(i>0)t=i,i=0;
saves two characters.Outside of a for loop, and even there is has can have an aroma of code smell, the only place I've seen as a good use for the comma operator is as part of a delete:
The only value over the alternative is you can accidently copy/paste only half of this operation if it is on two lines.
I also like it because if you do it out of habit, you'll never forget the zero assignment. (Of course, why p isn't inside somekind of auto_ptr, smart_ptr, shared_ptr, etc wrapper is a different question.)
You can overload it (as long as this question has a "C++" tag). I have seen some code, where overloaded comma was used for generating matrices. Or vectors, I don't remember exactly. Isn't it pretty (although a little confusing):
MyVector foo = 2, 3, 4, 5, 6;
The only time I have ever seen the
,
operator used outside afor
loop was to perform an assingment in a ternary statement. It was a long time ago so I cannot remeber the exact statement but it was something like:Obviously no sane person would write code like this, but the author was an evil genius who construct c statements based on the assembler code they generated, not readability. For instance he sometimes used loops instead of if statements because he preferred the assembler it generated.
His code was very fast but unmaintainable, I am glad I don't have to work with it any more.
I've seen it used in macros where the macro is pretending to be a function and wants to return a value but needs to do some other work first. It's always ugly and often looks like a dangerous hack though.
Simplified example:
Here
B=SomeMacro(A)
"returns" the result of Permute(A) and assigns it to "B".Given @Nicolas Goy's citation from the standard, then it sounds like you could write one-liner for loops like:
But good God, man, do you really want to make your C code more obscure in this way?