Uses of C comma operator [duplicate]

2018-12-31 14:56发布

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?

20条回答
看风景的人
2楼-- · 2018-12-31 15:34

It can be handy for "code golf":

Code Golf: Playing Cubes

The , in if(i>0)t=i,i=0; saves two characters.

查看更多
呛了眼睛熬了心
3楼-- · 2018-12-31 15:36

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:

 delete p, p = 0;

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.)

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 15:37

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;

查看更多
美炸的是我
5楼-- · 2018-12-31 15:37

The only time I have ever seen the , operator used outside a for 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:

int ans = isRunning() ? total += 10, newAnswer(total) : 0;

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.

查看更多
临风纵饮
6楼-- · 2018-12-31 15:39

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:

#define SomeMacro(A) ( DoWork(A), Permute(A) )

Here B=SomeMacro(A) "returns" the result of Permute(A) and assigns it to "B".

查看更多
路过你的时光
7楼-- · 2018-12-31 15:39

Given @Nicolas Goy's citation from the standard, then it sounds like you could write one-liner for loops like:

int a, b, c;
for(a = 0, b = 10; c += 2*a+b, a <= b; a++, b--);
printf("%d", c);

But good God, man, do you really want to make your C code more obscure in this way?

查看更多
登录 后发表回答