tags:

views:

241

answers:

3

What is meaning of using the second parameter with a comma in the below code?

int *num = new int[25,2];
+15  A: 

That's the comma operator in action: it evaluates it's operand and returns the last one, in your case 2. So that is equivalent with:

int *num = new int[2];

It's probably safe to say that the 25,2 part was not what was intended, unless it's a trick question.

Edit: thank you Didier Trosset.

Eugen Constantin Dinca
Does the comma operator return the first operand or the last one?
AraK
It returns the last one.
Didier Trosset
This looks alot like Didiers answer.. Did you use the same source, or do programmers just think alike :)
Default
Nice copy-paste. Might want to fix the grammar next time ;)
Peter Alexander
@Peter Alexander: Might want to check the 'answered x mins ago' part ;)I've thanked Didier for pointing that it returns the last not the first like I initially said.
Eugen Constantin Dinca
if nobody has overloaded this operator (i don't know, if it possible for integer).
LonliLokli
@Lonli: It is not; at least one operand has to be a user defined type.
Dennis Zickefoose
+12  A: 

That's the comma operator in action: it evaluates it's operand and returns the last one, in your case 2. So that is equivalent with:

int *num = new int[2];
Didier Trosset
Please note that the text of the posts on SO is published with a license that requires attribution. You may copy-paste, but you should cite the sources.
avakar
Eugen Dinca posted the exact same answer 2 minutes before you. I'm not sure re-posting his answer just to correct one word is more efficient (and more elegant) than just pointing out the error so he can fix his answer.
ereOn
I didn't thought I could edit others' answers. I actually first pointed the error in a comment, you can see it, and a couple of minutes after copied-pasted his answer to correct it. With my apologies for the non correct behavior.
Didier Trosset
+7  A: 

You are using the comma operator, which is making the code do something that you might not expect at a first glance.

The comma operator evaluates the LHS operand then evaluates and returns the RHS operand. So in the case of 25, 2 it will evaluate 25 (doing nothing) then evaluate and return 2, so that line of code is equivalent to:

int *num = new int[2];
Peter Alexander