Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting address of rvalue in C99

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?

http://ideone.com/iMwNVr

like image 394
justanothercoder Avatar asked Nov 17 '14 14:11

justanothercoder


1 Answers

(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.

like image 140
Yu Hao Avatar answered Oct 21 '22 10:10

Yu Hao