https://gcc.gnu.org/bugzilla/show_bug.cgi?id=125995

            Bug ID: 125995
           Summary: constexpr struct initialization leads to unexpected
                    results
           Product: gcc
           Version: 16.1.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: victarv at gmail dot com
  Target Milestone: ---

The following code unexpectedly prints `-1`, instead of the expected `0`.

```
#include <stdint.h>
#include <stdio.h>
#include <string.h>

struct Foo {
    uint8_t baz;
    uint8_t qux;
};

struct Bar {
    struct Foo foo;
};

static constexpr struct Bar b = {
    .foo = {
        .baz = 1
    }
};

static void unused() {
    struct Foo f = b.foo;
}

int main() {
    uint8_t a = 1;
    int diff = memcmp(&b.foo.baz, &a, 1);
    printf("%d\n", diff);
    return 0;
}
```

The following changes to the code fixes the issue:
1. Removing the `unused` function.
2. Explicitly assigning 0 to `qux` in the constexpr initializer.
3. Adding `struct Bar t = b;` in `unused`.
4. Changing `constexpr` to `const`.

Compiled with `gcc -std=c23`.

Reply via email to