Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The limitations of the comma operator

I have read this question and I want to add to it that what are the things that can not be done using the comma operator. This has confused me a lot, as I can do this:

int arr[3];
arr[0]=1,arr[1]=2,arr[2]=3;

But when I do:

int arr[3],arr[0]=1,arr[1]=2,arr[2]=3;

It gives me a compiler error.

I want to ask that what are the limitations of the comma operator in real practice?


1 Answers

One thing to realize is that not all uses of a comma in C are instances of the comma operator. Changing your second example to be a syntactically declaration:

int a0=1,a1=2,a2=3;

the commas are not operators, they're just syntax required to separate instances of declarators in a list.

Also, the comma used in parameter/argument lists is not the comma operator.

In my opinion the use of the comma operator is almost always a bad idea - it just causes needless confusion. In most cases, what's done using a comma operator can be more clearly done using separate statements.

Two exceptions that come to mind easily are inside the control clauses of a for statement, and in macros that absolutely need to cram more than one 'thing' into a single expression, and even this should only be done when there's no other reasonable option).

like image 82
Michael Burr Avatar answered Jan 28 '26 17:01

Michael Burr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!