Skip to content

C23 typeof() cannot be used in a union or struct with a compound literal with a non-constant initializer #151769

@g-berthiaume

Description

@g-berthiaume

Hi,

I just encountered what seems to be the same problem as #25689, but with C23 typeof() instead of the __typeof__() intrinsics.
Let me know if this issue is redundant.

Here's a reproducible example:

How to reproduce:

#include <stdlib.h>

int main(void)
{
    int x = 3;
    struct { typeof((int){x}) y; };
    return 0;
}

Compile with

clang -std=c23 .\main.c -o main
.\main.c:6:26: error: initializer element is not a compile-time constant
    6 |     struct { typeof((int){x}) y; };
      |                          ^~~
1 error generated.

The error has been reproduced on Windows:

clang version 20.1.8
Target: x86_64-pc-windows-msvc
Thread model: posix

The error has been reproduced on Linux (Ubuntu WSL):

Ubuntu clang version 18.1.8 (++20240731024944+3b5b5c1ec4a3-1~exp1~20240731145000.144)
Target: x86_64-pc-linux-gnu
Thread model: posix

Motivation

While a minimal reproducible example is nice, here's an example to motivate the PR:
The creation of a UNION_CAST(int, my_var) macro for safe C type punning.

// :: UNION_CAST
#define UNION_CAST(NEW_TYPE, VAR)        \
        (((union {                       \
                 typeof(VAR) before;    \
                 NEW_TYPE after;         \
         }){.before = (VAR)})            \
             .after)

Thanks for your work!

Metadata

Metadata

Assignees

No one assigned

    Labels

    c23clang:frontendLanguage frontend issues, e.g. anything involving "Sema"duplicateResolved as duplicate

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions