Home > Back-end >  C: how to return a struct literal without mentioning its type name?
C: how to return a struct literal without mentioning its type name?

Time:01-09

We can return struct literal from a function by casting anonymous literal initializer to the return type:

struct foo f() {
    return (struct foo) { .bar = 42 };
}

Is it possible without mentioning struct foo anywhere in the initializer? Separate declaration:

struct foo result = {
    .bar = 42
};
return result;

will not do, as it still explicitly mentions the struct foo type.

Is it possible to get the return type of enclosing function with typeof? I tried:

  • return (typeof(#__func__())) { .bar = 42 };
  • and return (__auto_type) { .bar = 42 };,

but apparently C's type inference doesn't go outside of a single expression.

I'm writing a preprocessor macro and would like to avoid the extra argument for the type.

gcc specific solutions are welcome.

CodePudding user response:

No. It is not possible. Both a declaration (6.7.6) and an initialization of compound literals requires a type specifier (6.5.2.5, 6.7.9).

CodePudding user response:

Per the latest public C11 standard draft at the time of writing, "6.5.2.5 Compound literals" (which are struct initializers):

A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal.

(bold emphasis is mine).

Indeed, it has nothing to do with type cast, except for similar syntax.

I believe, this is the only way in C standard to specify struct literals.

  • Related