views:

164

answers:

5

Today, I found out that you can write such code in C++ and compile it:

int* ptr = new int(5, 6);

What is the purpose of this? I know of course the dynamic new int(5) thing, but here i'm lost. Any clues?

+13  A: 

You are using the comma operator, it evaluates to only one value (the rightmost).

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

Source

The memory address that the pointer is pointing to is initialized with a value of 6 above.

Brian R. Bondy
Since operator (,) discards its first operand, it's the same as new int(6). Right?
Stringer Bell
Yes that is correct. But you could have some other expression instead of 5 that you would want evaluated and 6 returned. It will evaluate all expressions but return the last one.
Brian R. Bondy
http://msdn.microsoft.com/en-us/library/zs06xbxh(VS.80).aspx But at that link Microsoft says "Where the comma is normally used as a separator (for example in actual arguments to functions or aggregate initializers), the comma operator and its operands must be enclosed in parentheses." Wouldn't expression in int(expression) count as an argument list and therefore wouldn't the comma be evaluated as a seperator?
Bob
@Bob: Not in VC++ at least
Brian R. Bondy
I guess the new initializer is not a function nor an aggregate initializer.
Brian R. Bondy
FWIW, g++ parses it as a seperator, not a comma operator. Anybody familiar with the C++ spec know which is correct?
McPherrinM
+1  A: 

My compiler, g++, returns an error when attempting to do this.

What compiler or code did you see this in?

McPherrinM
Visual Studio 2008. I wrote that code.
Stringer Bell
It compiles in MSVC 6.0 and initializes the location ptr with value 6.
Rajendra Kumar Uppal
+1  A: 

I believe it is bug which meant to allocate some sort of 2D array. You can't do that in C++ however. The snippet actually compiles because it's utilizing the comma operator, which returns the last expression and ignores the results of all the others. This means that the statement is equivalent to:

int* ptr = new int(6);
MikeP
+1  A: 

The 5 is ignored. this allocates an int on the heap and initializes it to (5,6).

the result of a set of statements separated by the comma operator is the value of the last statement, so the int is initialized to 6

John Knoeller
+1  A: 

Simply do this:

int* ptr = new int(6);

As far as comma operator is concerned, use it when you can't do the desired task without it. There is no use of applying tricks such as:

int* ptr = new int(5, 6);
Rajendra Kumar Uppal