| 1 |
// PR c++/91353 - P1331R2: Allow trivial default init in constexpr contexts. |
| 2 |
// { dg-do compile { target c++20 } } |
| 3 |
// Test basic use. |
| 4 |
|
| 5 |
struct S { |
| 6 |
int i; |
| 7 |
constexpr S(bool b) { |
| 8 |
if (b) |
| 9 |
i = 42; |
| 10 |
} |
| 11 |
}; |
| 12 |
constexpr S s1(true); |
| 13 |
constexpr S s2(false); // { dg-error "not a constant expression" } |
| 14 |
|
| 15 |
constexpr int |
| 16 |
fn1 (int x) |
| 17 |
{ |
| 18 |
int a; |
| 19 |
a = 5; |
| 20 |
return x + a; |
| 21 |
} |
| 22 |
|
| 23 |
static_assert (fn1 (2) == 7); |
| 24 |
|
| 25 |
constexpr int |
| 26 |
fn2 (int x) |
| 27 |
{ |
| 28 |
const int a; // { dg-error "uninitialized .const a." } |
| 29 |
constexpr int b; // { dg-error "uninitialized .const b." } |
| 30 |
return x; |
| 31 |
} |
| 32 |
|
| 33 |
constexpr int |
| 34 |
fn3 (int x) |
| 35 |
{ |
| 36 |
int a; // { dg-message ".int a. is not const" } |
| 37 |
return x + a; // { dg-error "the value of .a. is not usable in a constant expression" } |
| 38 |
} |
| 39 |
|
| 40 |
constexpr int a = fn3 (5); // { dg-message "in .constexpr. expansion of" } |
| 41 |
|
| 42 |
constexpr int |
| 43 |
fn4 () |
| 44 |
{ |
| 45 |
struct S { int a = -5; int b; } s; |
| 46 |
return s.a; |
| 47 |
} |
| 48 |
|
| 49 |
static_assert (fn4 () == -5); |
| 50 |
|
| 51 |
constexpr int |
| 52 |
fn5 () |
| 53 |
{ |
| 54 |
struct S { int a = 9; int b; } s; |
| 55 |
return s.b; // { dg-error "accessing uninitialized member" } |
| 56 |
} |
| 57 |
|
| 58 |
constexpr int b = fn5 (); // { dg-message "in .constexpr. expansion of" } |
| 59 |
|
| 60 |
constexpr int |
| 61 |
fn6 () |
| 62 |
{ |
| 63 |
int a; |
| 64 |
return 42; |
| 65 |
} |
| 66 |
|
| 67 |
static_assert (fn6 () == 42); |
| 68 |
|
| 69 |
constexpr int |
| 70 |
fn7 (bool b) |
| 71 |
{ |
| 72 |
int a; // { dg-message ".int a. is not const" } |
| 73 |
if (b) |
| 74 |
a = 42; |
| 75 |
return a; // { dg-error "the value of .a. is not usable" } |
| 76 |
} |
| 77 |
|
| 78 |
static_assert (fn7 (true) == 42); |
| 79 |
static_assert (fn7 (false) == 42); // { dg-error "non-constant condition" } |
| 80 |
// { dg-message "in .constexpr. expansion of" "" { target *-*-* } .-1 } |
| 81 |
|
| 82 |
constexpr int |
| 83 |
fn8 (int n) |
| 84 |
{ |
| 85 |
int r; |
| 86 |
switch (n) |
| 87 |
{ |
| 88 |
case 1: |
| 89 |
r = n; |
| 90 |
return r; |
| 91 |
case 42: |
| 92 |
r = n; |
| 93 |
return r; |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
static_assert (fn8 (1) == 1); |
| 98 |
static_assert (fn8 (42) == 42); |