| 1 |
// { dg-do compile { target c++20 } } |
| 2 |
|
| 3 |
union U { int a; int b; int c[2]; }; |
| 4 |
|
| 5 |
constexpr int test1() { |
| 6 |
U u; |
| 7 |
u.a = 10; |
| 8 |
*&u.b = 20; // { dg-error "accessing" } |
| 9 |
return u.b; |
| 10 |
} |
| 11 |
constexpr int x1 = test1(); // { dg-message "in .constexpr. expansion" } |
| 12 |
|
| 13 |
constexpr int test2() { |
| 14 |
U u; |
| 15 |
u.a = 10; |
| 16 |
(0, u.b) = 20; // { dg-error "accessing" } |
| 17 |
return u.b; |
| 18 |
} |
| 19 |
constexpr int x2 = test2(); // { dg-message "in .constexpr. expansion" } |
| 20 |
|
| 21 |
constexpr int test3() { |
| 22 |
U u; |
| 23 |
u.a = 0; |
| 24 |
int* p = &u.b; |
| 25 |
p[u.a] = 10; // { dg-error "accessing" } |
| 26 |
return u.b; |
| 27 |
} |
| 28 |
constexpr int x3 = test3(); // { dg-message "in .constexpr. expansion" } |
| 29 |
|
| 30 |
constexpr int test4() { |
| 31 |
U u; |
| 32 |
u.a = 0; |
| 33 |
int* p = &u.b; |
| 34 |
u.a[p] = 10; // { dg-error "accessing" } |
| 35 |
return u.b; |
| 36 |
} |
| 37 |
constexpr int x4 = test4(); // { dg-message "in .constexpr. expansion" } |
| 38 |
|
| 39 |
struct S { U u[10]; }; |
| 40 |
constexpr int test5() { |
| 41 |
S s; |
| 42 |
s.u[4].a = 10; |
| 43 |
6[s.u].b = 15; |
| 44 |
return 4[s.u].a + s.u[6].b; |
| 45 |
} |
| 46 |
static_assert(test5() == 25); |
| 47 |
|
| 48 |
constexpr int test6() { |
| 49 |
U u; |
| 50 |
u.a = 5; |
| 51 |
u.c[0] = 3; |
| 52 |
1[u.c] = 8; |
| 53 |
return 1[u.c] + u.c[0]; |
| 54 |
} |
| 55 |
static_assert(test6() == 11); |
| 56 |
|
| 57 |
constexpr int test7() { |
| 58 |
U u; // default initialisation leaves no member initialised |
| 59 |
int* p = &u.a; |
| 60 |
*p = 10; // { dg-error "accessing" } |
| 61 |
return *p; |
| 62 |
} |
| 63 |
constexpr int x7 = test7(); // { dg-message "in .constexpr. expansion" } |
| 64 |
|
| 65 |
constexpr int test8() { |
| 66 |
U u {}; // value initialisation initialises first member |
| 67 |
int* p = &u.a; |
| 68 |
*p = 8; |
| 69 |
return *p; |
| 70 |
} |
| 71 |
static_assert(test8() == 8); |
| 72 |
|
| 73 |
union V { int :0; static int x; void foo(); int a; }; |
| 74 |
constexpr int test9() { |
| 75 |
V v {}; // should skip zero-width bit fields, static members, and functions |
| 76 |
int* p = &v.a; |
| 77 |
*p = 9; |
| 78 |
return *p; |
| 79 |
} |
| 80 |
static_assert(test9() == 9); |