Question

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?

Was it helpful?

Solution

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

OTHER TIPS

You can use the comma operator most anywhere that an expression can appear. There are a few exceptions; notably, you cannot use the comma operator in a constant expression.

You also have to be careful when using the comma operator where the comma is also used as a separator, for example, when calling functions you must use parentheses to group the comma expression:

void f(int, bool);

f(42, 32, true);   // wrong
f((42, 32), true); // right (if such a thing can be considered "right")

Your example is a declaration:

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

In a declaration, you can declare multiple things by separating them with the comma, so here too the comma is used as a separator. Also, you can't just tack on an expression to the end of a declaration like this. (Note that you can get the desired result by using int arr[3] = { 1, 2, 3 };).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top