Reputation: 1890
The following code compiles and works:
#include <stdio.h>
void print(void* x)
{
printf("%d", *(int*)x);
}
int main()
{
print(&((struct { int x, y; }){ .x = 1, .y = 2 })); //outputs 1
return 0;
}
Why compiler allows me to get address of rvalue? Is this defined behaviour?
Upvotes: 9
Views: 409
Reputation: 122443
(struct { int x, y; }){ .x = 1, .y = 2 }
is a compound literal, and:
C99 §6.5.2.5 Compound literals
If the type name specifies an array of unknown size, the size is determined by the initializer list as specified in §6.7.8, and the type of the compound literal is that of the completed array type. Otherwise (when the type name specifies an object type), the type of the compound literal is that specified by the type name. In either case, the result is an lvalue.
Upvotes: 12