Archived

This topic is now archived and is closed to further replies.

Coz

What really is the comma operator?

Recommended Posts

What does the comma(,) operator really do in C++ or C, and in which situations it might be inside an array(please be as technical as posible).

Share this post


Link to post
Share on other sites
its a separator.
ie. when you call a function with two parameters:

myFunc(param1, param2)

the comma(,) tells the compiler that param1 and param2 is not the same parameter.

and when you define an array : int array[5] { 1, 2, 3, 4, 5 };
the comma tells the compiler to move on to the next element of the array.

thats pretty much what it does..
hope that helps

[edited by - branhield on November 8, 2002 1:14:14 PM]

Share this post


Link to post
Share on other sites
It does much more than that. The comma is the sequencing operator. It can be used to force a certain evaluation order in expressions. It can also be used to sequence several expressions as part of eg. a single argument.

Example: for( a=1, i=a;; ) ...

Here the evaluation order is forced to first evaluate a=1, before i=a. This guarantees that a is set to 1 before assigning it to i.

Example 2: while( c = a+1, b<4 ) ...



[edited by - Yann L on November 8, 2002 1:20:51 PM]

Share this post


Link to post
Share on other sites
quote:
What if you used it like

char Array[255,255];

What would the effect be?



When doing an expression like that, it would use the last expression in the sequence separated by commas as the substript of the array.

So Array[255,255] is the same as Array[255]

To be more clear:

Array[2,3] is the same as Array[3]

And finally

Array[1,8,2+4,-3,3*x,0,54] is the same as Array[54]

All that the commas do in those cases are ensure that the expressions are evaluated in that order. In these cases it doesn't make too much sense, but, for instance, if one of the expressions effected the value of the last in the sequence, then the commas insure that the change happens first IE:

Array[ MyFunction( &a ), a ];

insures that the function is called first, which can be important if MyFunction changes the value of a

However, this makes what you're trying to do less obvious to most people, so you generally want to avoid something like that.

[edited by - Matt Calabrese on November 8, 2002 2:25:00 PM]

Share this post


Link to post
Share on other sites
Thanx people, that helps a lot. I was doing my my code and i put the arrays with commas, and the thing compiled, and of course the result wasn''t the expected and fixed it but i was just curious of what the hell i was doing. All the knowledge contained here becomes now a part of our experience as programmers.

Share this post


Link to post
Share on other sites