Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this legal C/C++? `int* p = (int[]) {1,2,3} ;`

This answer of mine generated some comments claiming that the following construct is not legal C/C++:

void f (int* a) ;
f ((int[]){1,2,3,4,0}) ;

(see this ideone link for a full program). But we weren't able to resolve the issue. Can anybody shed any light on this? What do the various standards have to say?

like image 858
TonyK Avatar asked Jan 14 '12 09:01

TonyK


People also ask

What is the meaning of int (* a 3?

The int (*a)[3] is a pointer to an array of 3 int (i.e. a pointer to int[3] type). The braces in this case are important.

What does int * mean in C?

int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.

What is int& in C++?

int& is a reference. To be more precise, a reference variable is simply an alternative name of an existing variable.


2 Answers

It's valid C99 as far as I can tell - that's passing a compound literal.

The C99 standard has this as an example (§6.5.2.5/9):

EXAMPLE 1 The file scope definition

int *p = (int []){2, 4};

initializes p to point to the first element of an array of two ints, the first having the value two and the second, four. The expressions in this compound literal are required to be constant. The unnamed object has static storage duration.

Note that the (int []) thing is not a cast here.

This is not a valid C++ construct though, compound literals are not part of the C++ standard (C++11 included). Some compilers allow it as an extension. (GCC does, pass -Wall -pedantic to get a diagnostics about it. IBM xlC allows it as an extension too.)

like image 74
Mat Avatar answered Oct 08 '22 09:10

Mat


The expression passed as argument to the function is an example of a compound literal. These are legal in C99, but not in C++98.

See for example section 6.4.4 "Constants" and 6.8 "Statements and blocks" in N897 "A draft rationale for the C99 standard." See also this section of GCC documentation.

like image 38
Adam Zalcman Avatar answered Oct 08 '22 09:10

Adam Zalcman