What is the meaning of using the second parameter with a comma in the below code?
int *num = new int[25,2];
Join Stack Overflow to learn, share knowledge, and build your career.
What is the meaning of using the second parameter with a comma in the below code?
int *num = new int[25,2];
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.
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];
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];
// Declare a single-dimensional array
int[] array1 = new int[5];
// Declare and set array element values
int[] array2 = new int[] { 1, 3, 5, 7, 9 };
// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };
// Declare a two dimensional array
int[,] multiDimensionalArray1 = new int[2, 3];
// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
// Declare a array
int[][] Array = new int[6][];
// Set the values of the first array in the array structure
Array[0] = new int[4] { 1, 2, 3, 4 };
new (int[25, 2])
is not legal code. – Johannes Schaub - litb Jun 24 '10 at 9:57new int(25, 2)
? Oh, wait, isnew (int [25])
andnew int (25)
equivalent? – Lazer Jun 24 '10 at 14:1325, 2
does not syntactically match it and neither semantically. So even if you write it asnew (int[(25, 2)])
it is illegal code. Doesn't need a comma operator to explain it - evenint n = 1; new (int[n]);
is illegal -n
isn't a constant expression. – Johannes Schaub - litb Jun 24 '10 at 16:3125, 2
is a constant expression andnew (int[25, 2])
does compile. – avakar Jun 24 '10 at 18:16