C 2011 (N1570) 6.5.2.5 5 says:
If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.
So the compound literal you show has automatic storage duration. The C standard does not specify where such objects are in memory. It is up to the C implementation to organize memory. Typically, an object with automatic storage duration is created on the stack, but there are other methods by which an implementation might manage such objects.
In particular, suppose you record the value of p
elsewhere and recursively call the routine containing this compound literal. When the routine initializes p
again, there is a second instance of the compound literal. They are actually different objects, and the C standard requires that their addresses be different. So, if you print the two pointers, they will have different values. However, if the optimizer is able to determine that you do not do this, and that two pointers to different instances of the compound literal are never compared, and there is no other observable behavior (as defined by the C standard) that can distinguish them, then the C implementation is free to use one actual instance of the compound literal instead of creating a new one each time. In this case, the compiler could keep the compound literal in a data section instead of on the stack.
Here is code that demonstrates two instances of the same compound literal have different addresses:
#include <math.h>
#include <stdio.h>
void foo(int *q)
{
int *p = (int []) { 2, 3 };
if (!q)
foo(p);
else
printf("p = %p, q = %p.\n", (void *) p, (void *) q);
}
int main(void)
{
foo(0);
return 0;
}
String literals are different. C 2011 (N1570) 6.4.5 6 says:
In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.
So a string literal denotes an object with static storage duration. There is only one instance of it even if a routine containing it is called recursively.