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?
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.
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.
int& is a reference. To be more precise, a reference variable is simply an alternative name of an existing variable.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With