Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

What compiler or code did you see this in?

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

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

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top