Search code examples
cstructcompound-literals

How to initialize a compound literal with a value of the same type?


for example:

typedef struct S { int i; char c; } S;

#define MAKE_CLITERAL(T) ((typeof(T)) {T})

int main()
{
    S s = {.i = 500, .c = 'a'};

    S s2 = MAKE_CLITERAL(s); // doesn't compile
}

I want the macro MAKE_CLITERAL to turn any value into a compound literal.

such that doing something like MAKE_CLITERAL( 10 ) and MAKE_CLITERAL( s ) both make compound literals of their type.

I tried doing this:

#define MAKE_CLITERAL(T) ( (typeof(T)){} = T );

but it doesn't behave exactly like a compound literal, so this doesn't work:

&MAKE_CLITERAL(s); // compiler says this is an rvalue

Is there a way to initialize a compound literal by using a value of the same type?


Solution

  • You can wrap the object into an untagged struct type created within the compound literal.

    #define MAKE_CLITERAL(T) (struct { typeof(T) t; } ) { T }.t