Exam 5 · Expressions, evaluation order and constant evaluation
25 questions on evaluation order, integral promotions and arithmetic conversions, shifts and out-of-range conversions, pointer comparison, the conditional operator, lambda captures and closure types, structured bindings, constant evaluation, immediate functions and static initialization order, with the emphasis on telling UB, unspecified behavior and implementation-defined behavior apart.
Key points
- Scope: sequenced, indeterminately sequenced and unsequenced evaluations in [intro.execution]; integral promotions, the usual arithmetic conversions, shifts, division, floating-point and enumeration conversions; pointer comparison; the value categories of the conditional and comma operators; lambda captures, closure types, structured bindings; core constant expressions in [expr.const],
constevaland immediate escalation,constinit,std::is_constant_evaluated, dynamic allocation at compile time; dynamic initialization order across translation units. - Question types: 15 verdict, 7 multiple choice, 3 open-ended, roughly increasing in difficulty.
- For verdict questions, answer with the most severe property of the whole program. Unless a question says otherwise, assume
shortis 16 bits andintis 32 bits. - Suggested time: 90 minutes. After answering, write down the clause numbers yourself before opening the explanation to check.
1. Evaluation order#
Judge this program.
int main() {
int i = 0;
i = i++ + 1;
return i;
}Answer and explanation
Answer: well-formed with well-defined behavior; main returns 1.
- [intro.execution]/10 says that if a side effect on a memory location is unsequenced relative to another side effect on the same location or to a value computation using it, the behavior is undefined. There are two side effects on
ihere: the increment ofi++and the write of=. - [expr.assign]/1 says the right operand of an assignment is sequenced before the left operand, and the assignment itself happens after the value computations of both operands. By the last sentence of [intro.execution]/8, the right operand being sequenced before the left means all of its value computations and side effects come first. So the increment of
i++completes first, and only then is0 + 1written. - Example 3 in [intro.execution]/10 contains exactly this line, with the comment "the value of i is incremented".
ub is the C++14 answer. Back then the side effect of the assignment was sequenced only after the value computations of the operands, with no ordering relative to the side effect of i++. C++17 added the right-before-left rule through P0145R3.
One change makes it UB: read i once more in the right operand. The two operands of + are still unsequenced, so the modification by i++ conflicts with the read of i on the other side.
int main() {
int i = 0;
i = i++ + i;
return i;
}For more examples see Order of evaluation.
Judge this program.
#include <cstdio>
void f(int a, int b) { std::printf("%d %d\n", a, b); }
int main() {
int i = 0;
f(i++, i++);
}Answer and explanation
Answer: unspecified behavior. It prints 0 1 or 1 0; it is not UB.
- [expr.call]/8: the initialization of each parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.
- [intro.execution]/8: of two indeterminately sequenced evaluations, one always happens before the other; it is just unspecified which, and they do not interleave.
- So the two
i++are not unsequenced, and the UB condition of [intro.execution]/10 does not hold. What remains is an unspecified order, which is unspecified behavior in the sense of [intro.abstract]/3.
Clang 23 prints 0 1 and also gives a -Wunsequenced warning (multiple unsequenced modifications). Under the rules since C++17, that warning is a false positive: the two modifications are not unsequenced. In C++14 the arguments really were unsequenced, and this line was UB.
Each of the four lines below appears on its own in test (with i initially 0). Which line has undefined behavior?
void f(int, int) {}
void test() {
int i = 0;
int a[4]{};
a[i] = i++; // A
i = (i++, i); // B
f(i = 1, i = 2); // C
(void)((i = 1, 0) + (i = 2, 0)); // D
}- A.
a[i] = i++; - B.
i = (i++, i); - C.
f(i = 1, i = 2); - D.
(i = 1, 0) + (i = 2, 0)
Answer and explanation
Answer: D.
- D: the comma operator only guarantees left-before-right within each pair of parentheses ([expr.comma]/1). The two operands of
+are unsequenced (first sentence of [intro.execution]/10), so the two assignments toiare unsequenced relative to each other: UB. The(u.x = 1, 0) + (u.y = 2, 0)in example 3 of [intro.execution]/10 has the same structure, where the two union members occupy the same memory location. - A: per [expr.assign]/1 the right operand is evaluated first;
i++yields 0 andibecomes 1; then the left operanda[1]is evaluated and 0 is written. Well-defined. - B: the comma operator sequences the side effect of
i++before the read ofion its right ([expr.comma]/1), and the whole comma expression is the right operand of the assignment, sequenced before the assignment. The result isi == 1. - C: the argument initializations are indeterminately sequenced ([expr.call]/8) and do not interleave; whether
iends up 1 or 2 is unspecified, but it is not UB.
Clang gives -Wunsequenced for both C and D, and for C it is a false positive. Going by the warnings alone, you would judge C to be UB as well.
Judge this program.
constexpr int f() {
int i = 0;
return i++ + i++;
}
static_assert(f() == 1);
int main() {}Answer and explanation
Answer: well-formed.
- The condition of
static_assertis a constant expression, andf()is evaluated as a core constant expression. - [intro.execution]/16 says that when evaluated as a core constant expression, operands and subexpressions that would otherwise be unsequenced or indeterminately sequenced are evaluated in lexical order. So the left
i++completes first (value 0,ibecomes 1), then the righti++is evaluated (value 1), and the result is 1. - The two modifications are now ordered, the UB of [intro.execution]/10 does not arise, and so there is no undefined operation for [expr.const.core]/2.8 to diagnose.
The tempting answer is error: normally, constant evaluation that hits UB is not a constant expression. But here there is no UB in constant evaluation at all. The lexical-order rule is new wording added after C++23.
Clang 23 accepts this code and gives a -Wunsequenced warning on the return line. The warning is justified: when the same function is called at run time, [intro.execution]/16 does not apply, and i++ + i++ is still UB.
constexpr int f() {
int i = 0;
return i++ + i++;
}
int main() { return f(); } // not a manifestly constant-evaluated context; evaluated by run-time rulesWhat does this program return since C++17? Derive the result step by step from the rules of [expr.assign], and explain why it was UB in C++14.
int main() {
int x = 3, y = 5;
x ^= y ^= x ^= y;
return x * 10 + y;
}Answer and explanation
Answer: it returns 53, that is, x == 5 and y == 3.
- Assignment operators group right to left ([expr.assign]/1), so the expression is
x ^= (y ^= (x ^= y)). - For the outermost
^=: the whole right operandy ^= (x ^= y)is sequenced before the left operandx, and the compound assignment itself happens after the value computations of both operands ([expr.assign]/1). [expr.assign]/6 saysE1 op= E2is equivalent toE1 = E1 op E2except thatE1is evaluated only once; the compound assignment reads the old value ofxat this step, so it reads the value already modified by the inner levels. - The same reasoning applies level by level going inward:
- innermost
x ^= y:x = 3 ^ 5 = 6; - middle
y ^= 6:y = 5 ^ 6 = 3; - outermost
x ^= 3:x = 6 ^ 3 = 5.
- innermost
- In our tests it returns 53.
C++14 only specified that the side effect of an assignment is sequenced after the value computations of its operands, not that the side effects of the right operand come before the left operand. The two writes to x were in fact ordered (the side effect of the inner assignment precedes the inner value computation, and the outer assignment comes after it); the problem was the read: the outermost ^= reading the old value of x was unsequenced relative to the innermost modification of x, which was UB under the [intro.execution] rules of the time. C++17's P0145R3 gave assignment its right-before-left ordering, and only then did this line acquire a definite result.
2. Integral promotions, arithmetic conversions and out-of-range values#
What does this program print?
#include <cstdio>
int main() {
unsigned short us = 1;
std::printf("%d %d %d\n", -1 < 0u, -1 < us, us - 2 < 0);
}- A.
0 0 0 - B.
0 1 1 - C.
1 1 1 - D.
0 1 0
Answer and explanation
Answer: B; it prints 0 1 1.
-1 < 0u: relational operators apply the usual arithmetic conversions to arithmetic operands ([expr.rel]/3).intandunsigned inthave the same rank, so per [expr.arith.conv]/1.5.3.1 the common type isunsigned int.-1is converted modulo 2^N per [conv.integral]/3 toUINT_MAX, and the comparison is false.-1 < us: integral promotion comes first.intcan represent every value ofunsigned short, sousis promoted toint([conv.prom]/2); twoints are compared, and the result is true.us - 2 < 0:usis likewise promoted toint,1 - 2gives-1, which is less than 0: true.
Items 2 and 3 depend on the widths of the integer types, which are implementation-defined ([basic.fundamental]/4). On a platform where int is only 16 bits, int cannot hold every value of unsigned short, us is promoted to unsigned int, and the output becomes 0 0 0. Clang 23 prints 0 1 1 and gives a -Wtautological-constant-out-of-range-compare warning for the second item.
To compare signed and unsigned numbers mathematically, use std::cmp_less; see Pitfalls of integer and floating-point arithmetic.
Judge this program.
unsigned mul(unsigned short a, unsigned short b) {
return a * b;
}
int main() {
return mul(65535, 65535) == 4294836225u;
}Answer and explanation
Answer: undefined behavior.
aandbare bothunsigned shortand are promoted tointbefore*per [conv.prom]/2 (intcan represent every value ofunsigned short). After the usual arithmetic conversions of [expr.mul]/2, the multiplication is performed inint.- The mathematical result 4294836225 is outside the range of
int. [expr.pre]/4: if the mathematical result of an arithmetic expression is not in the range of representable values for its type, the behavior is undefined. - That the return type is
unsigneddoes not matter; the conversion happens after the multiplication.
The tempting answer is ok: both operands are unsigned, so it looks as if arithmetic should wrap modulo 2^N. But wrapping is only a rule of integral conversions ([conv.integral]/3), and this multiplication is not done in an unsigned type at all.
Make the function constexpr and put it in a static_assert, and Clang reports value 4294836225 is outside the range of representable values of type 'int'; at run time UBSan reports signed integer overflow. Converting one operand to unsigned first makes it defined:
constexpr unsigned mul(unsigned short a, unsigned short b) {
return 1u * a * b;
}
static_assert(mul(65535, 65535) == 4294836225u);
int main() {}Which of the four declarations below is ill-formed?
#include <climits>
constexpr int a = -1 << 31; // A
constexpr int b = 1 << 31; // B
constexpr unsigned c = 1u << 32; // C
constexpr int d = -8 >> 1; // D- A.
a - B.
b - C.
c - D.
d
Answer and explanation
Answer: C.
- C: [expr.shift]/1 says the behavior is undefined if the right operand is negative, or greater than or equal to the width of the promoted left operand.
unsigned intis 32 bits wide, so shifting by 32 is UB, regardless of whether the left operand is unsigned. UB in constant evaluation makes the expression not a core constant expression ([expr.const.core]/2.8), and aconstexprvariable must be constant-initializable ([dcl.constexpr]/6), so the declaration ofcis ill-formed. Clang's note is shift count 32 >= width of type 'unsigned int'. - A and B: since C++20, the value of
E1 << E2is the unique value congruent to E1×2^E2 modulo 2^N ([expr.shift]/2), where N is the width of the result type. Both giveINT_MIN. Shifts are not among the arithmetic expressions covered by [expr.pre]/4, so there is no overflow UB. - D: [expr.shift]/3 says
E1 >> E2is E1/2^E2 rounded toward negative infinity, giving -4.
Before C++20, A was UB (left-shifting a negative number) and the result of D was implementation-defined. C++20 specified two's complement for signed integers (P1236R1), and the shift rules were rewritten accordingly. Clang 23 with -pedantic gives no warning for A, B or D:
#include <climits>
constexpr int a = -1 << 31;
constexpr int b = 1 << 31;
constexpr int d = -8 >> 1;
static_assert(a == INT_MIN && b == INT_MIN && d == -4);
int main() {}Judge this program.
#include <climits>
int rem(int a, int b) { return a % b; }
int main() {
return rem(INT_MIN, -1);
}Answer and explanation
Answer: undefined behavior.
The last sentence of [expr.mul]/4: if the quotient a/b is not representable in the type of the result, the behavior of both a/b and a%b is undefined. The mathematical result of INT_MIN / -1 is 2^31, which does not fit in int, so INT_MIN % -1 is UB too.
The tempting answer is ok: mathematically the remainder is 0, which is perfectly representable. The standard ties the two together because common hardware computes quotient and remainder with the same division instruction, and the instruction itself faults when the quotient overflows; x86 idiv, for example, raises an exception.
In our tests UBSan reports division of -2147483648 by -1 cannot be represented in type 'int'. In a static_assert, Clang rejects it and notes that 2147483648 is outside the range of int. With a divisor of 1 there is no problem:
#include <climits>
constexpr int rem(int a, int b) { return a % b; }
static_assert(rem(INT_MIN, 1) == 0);
int main() {}Judge this program.
unsigned to_u(double d) { return d; }
int main() {
return to_u(-1.0) == 0xFFFFFFFFu;
}Answer and explanation
Answer: undefined behavior.
return d;implicitly convertsdoubletounsigned, a floating-integral conversion. [conv.fpint]/1: the fractional part is truncated first, and if the truncated value cannot be represented in the destination type, the behavior is undefined.-1.0truncates to -1, whichunsignedcannot represent.
The tempting answer is ok, expecting UINT_MAX. The modular rule belongs only to conversions between integer types ([conv.integral]/3); it does not apply when the source is floating-point.
The boundary is after truncation: to_u(-0.5) truncates to 0, which is representable, so the result is defined.
constexpr unsigned to_u(double d) { return d; }
static_assert(to_u(-0.5) == 0);
int main() {}Put to_u(-1.0) in the initializer of a constexpr variable and Clang reports value -1 is outside the range of representable values of type 'unsigned int'; at run time UBSan gives the same diagnostic.
Judge this program.
enum E { A = 1, B = 4 };
enum G { M = -1, N = 1 };
constexpr E e = static_cast<E>(7);
constexpr G g = static_cast<G>(-2);
int main() { return int(e) + int(g); }Answer and explanation
Answer: well-formed; main returns 5.
- Neither enumeration has a fixed underlying type. [dcl.enum]/8 says their values are those of the hypothetical integer type with minimal width that can represent all the enumerators; values other than the enumerators themselves also belong to the enumeration.
- The enumerators of
Eare 1 and 4, both non-negative, so a 3-bit unsigned type suffices, and the range is 0 to 7. - The enumerators of
Gare -1 and 1, which need a signed type; 2-bit two's complement represents -2 to 1, and those four values are the range. - [expr.static.cast]/8: if the value is within the range of the enumeration it is unchanged; otherwise the behavior is undefined. Both 7 and -2 are within range, so both initializations are constant expressions.
The tempting answers are error or ub, on the grounds that there is no enumerator with value 7 or -2. The range is computed from bit width, not from the list of enumerators.
One step outside the range is UB, and in constant evaluation that makes it ill-formed. Clang's note is integer value 8 is outside the valid range of values [0, 7] for the enumeration type 'E':
enum E { A = 1, B = 4 };
enum G { M = -1, N = 1 };
constexpr E e = static_cast<E>(8); // error: outside [0, 7]
constexpr G g = static_cast<G>(-3); // error: outside [-2, 1]Written as enum E : int { ... }, the underlying type is fixed and the range is every value of int (first sentence of [dcl.enum]/8).
Judge this program against the current draft.
enum Color { Red, Green };
enum Fruit { Apple, Banana };
int main() {
return Red + Apple;
}Answer and explanation
Answer: ill-formed.
+ applies the usual arithmetic conversions to its two operands ([expr.add]). [expr.arith.conv]/1.3: if one operand is of enumeration type and the other is of a different enumeration type or a floating-point type, the expression is ill-formed.
This was deprecated in C++20 and removed in C++26 by P2864R2; it is now a hard error. ok is the answer for C++17 and earlier, when both enumerations were first promoted to int. Clang 23 with -std=c++2c reports invalid arithmetic between different enumeration types; the diagnostic group is -Wenum-enum-conversion, but in this mode it is an error by default.
The rule only blocks enumeration with a different enumeration, and enumeration with floating-point:
enum Color { Red, Green };
enum Fruit { Apple, Banana };
int a = Red + 1; // enumeration and integer: promoted, then added
int b = +Red + Apple; // unary + performs integral promotion first, so the left operand is already int
int main() { return a + b; }Unary + performs integral promotion on an enumeration ([expr.unary.op]/7), so the second line is int plus enumeration, not restricted by 1.3. Red == Apple and Red + 1.0 are ill-formed too; the equality operators also perform the usual arithmetic conversions ([expr.eq]/9).
Judge the return value of this program.
int main() {
char c = 200;
return c < 0;
}Answer and explanation
Answer: implementation-defined behavior.
- [basic.fundamental]/7: whether the underlying type of
charissigned charorunsigned charis chosen by the implementation. char c = 200;is an integral conversion frominttochar. [conv.integral]/3 says the result is the unique value congruent to 200 modulo 2^N. Ifcharis signed, that is -56 and the function returns 1; if unsigned, it is 200 and the function returns 0.- The conversion itself can never be UB. Since C++20, integral conversions are defined modulo 2^N for signed destination types too.
The tempting answer is ub, treating this conversion as signed overflow. Overflow UB applies only to the results of arithmetic expressions ([expr.pre]/4), and there is no arithmetic here.
On Apple arm64, where we tested, char is signed and the program returns 1, with Clang warning that the conversion changes value from 200 to -56; compiled with -funsigned-char, it returns 0.
3. Pointer comparison, the conditional operator, lambdas and structured bindings#
For each of the four comparisons below, answer: is the run-time result true, false or unspecified? Can it appear in a constant expression?
struct S {
int x;
private:
int y = 0;
public:
constexpr bool f() const { return &x < &y; }
};
int a[2];
int b;
// (1) &a[0] < &a[1]
// (2) S{}.f()
// (3) &a[0] < &b
// (4) &a[2] == &bAnswer and explanation
Answer: (1) true, constant; (2) true, constant; (3) unspecified, not constant; (4) unspecified, not constant.
- Of two different elements of the same array, the one with the larger subscript compares greater ([expr.rel]/4.1).
- Of two different non-static data members of the same object, the one declared later compares greater ([expr.rel]/4.2), under just two conditions: neither member is a subobject of zero size, and the class is not a union. The old rule also required both members to have the same access control; C++23 removed that condition through P1847R4, so the result is definitely true and may appear in a constant expression. Clang 23 still applies the old rule during constant evaluation and reports comparison of address of fields 'x' and 'y' of 'S' with differing access specifiers (public vs private) has unspecified value; the compiler has not caught up with the current draft.
aandbare unrelated complete objects; [expr.rel]/4.3 does not require either to compare greater, and [expr.rel]/5 says the result of<is then unspecified. Unspecified is not UB, and the program runs normally. But a relational operation with an unspecified result is not a core constant expression ([expr.const.core]/2.28). For a total order across objects, usestd::less<int*>.&a[2]is the past-the-end pointer ofa, and&bpoints to another complete object. [expr.eq]/4.1 says the result of an equality comparison in this case is unspecified, becausebmight happen to sit right aftera. It cannot appear in a constant expression either.
For comparison: &a[0] != &b is definitely true and can go in a static_assert. When two pointers point to different objects and neither is past-the-end, they compare unequal per [expr.eq]/4.3.
Which line is ill-formed?
void test(bool c) {
int i = 0;
long l = 0;
(c ? i : i) = 1; // A
(c ? i : throw 0) = 2; // B
(c ? i : l) = 3; // C
(c, i) = 4; // D
}- A. Line A
- B. Line B
- C. Line C
- D. Line D
Answer and explanation
Answer: C.
Assignment requires a modifiable lvalue as its left operand ([expr.assign]/1), so the question becomes the value category of each expression.
- A: the second and third operands are glvalues of the same type and the same value category, so the result is an lvalue of that type ([expr.cond]/5).
- B: when one operand is a throw-expression, the result has the type and value category of the other operand ([expr.cond]/2.1), here an
intlvalue. - C:
intandlongare different types and neither is a class type, so the conversion attempt of [expr.cond]/4 does not apply and [expr.cond]/5 is not satisfied either; we fall through to [expr.cond]/6, and the result is a prvalue; the usual arithmetic conversions are then applied per [expr.cond]/7.2, giving alongprvalue. A prvalue cannot be assigned to. - D: a comma expression has the value category of its right operand ([expr.comma]/1), an
intlvalue. Clang only warns that the left operand has no effect.
The tempting wrong answer is B, on the belief that throw makes the whole expression void or a prvalue. [expr.cond]/2.1 exists precisely to preserve lvalueness for code like c ? x : throw e.
One more case: if the third operand were a const int lvalue, [expr.cond]/4 would convert i to a const int lvalue, the result would be a non-modifiable lvalue, and the assignment would also be ill-formed, for a different reason.
Judge this program.
int main() {
int x = 0;
auto l = [=] { return sizeof(x); };
decltype(l) m;
return m();
}Answer and explanation
Answer: ill-formed.
- The operand of
sizeofis an unevaluated operand ([expr.sizeof]/1). [expr.prim.lambda.capture]/7 captures implicitly only when the expression is potentially evaluated, soxis not captured and the closure object has no data members. - But whether the closure type has a default constructor depends not on what is captured but only on whether there is a lambda-capture syntactically. [expr.prim.lambda.closure]/17: the closure type of a lambda with a lambda-capture has no default constructor, and its copy assignment operator is deleted.
[=]is a capture-default and counts as a lambda-capture. - So
decltype(l) m;finds no default constructor.
The tempting answer is ok, reasoning that nothing is captured, so the closure is as stateless as []. Drop the = and it works: since C++20, a closure type without a lambda-capture is default-constructible and assignable (P0624R2).
int main() {
int x = 0;
auto l = [] { return sizeof(x); }; // x in an unevaluated operand needs no capture
decltype(l) m;
m = l;
return m();
}Judge this program.
struct S {
int a : 4;
int b;
};
int sum() {
S s{1, 2};
auto [x, y] = s;
return [&] { return x + y; }();
}
int main() { return sum(); }Answer and explanation
Answer: ill-formed.
- Since C++20 structured bindings can be captured by lambdas: they are local entities as defined in [basic.pre]/9 (P1091R3, P1381R1).
Sis bound by data member. [dcl.struct.bind]/8:xis an lvalue referring toe.a, andais a bit-field, so that lvalue is a bit-field too.[&]implicitly captures bothxandyby reference ([expr.prim.lambda.capture]/7, [expr.prim.lambda.capture]/12). The last sentence of [expr.prim.lambda.capture]/12: a bit-field shall not be captured by reference.
Clang 23 rejects this code with the note non-const reference cannot bind to bit-field 'a'. Capturing x by copy, or capturing only y by reference, both work:
struct S {
int a : 4;
int b;
};
int sum() {
S s{1, 2};
auto [x, y] = s;
return [=] { return x + y; }() + [&y] { return y; }();
}
int main() { return sum(); } // returns 5Judge this program.
struct X {
int v = 7;
auto get() { return [=] { return v; }; }
};
int main() {
auto l = X{}.get();
return l();
}Answer and explanation
Answer: undefined behavior.
- In a member function,
vmeansthis->v. [expr.prim.lambda.capture]/7: an id-expression naming a non-static member potentially references*this, so*thisis implicitly captured. - Item 10.1 of [expr.prim.lambda.capture]/10 explicitly excludes
*thisfrom capture by copy, so it is captured by reference ([expr.prim.lambda.capture]/12): the closure stores thethispointer, not a copy ofv. This implicit capture is deprecated ([depr.capture.this]/1), but the program is still well-formed. X{}is a temporary, destroyed at the end of the full-expression ([class.temporary]/4). Afterwardl()accessesvthrough the danglingthis, which is UB per item 7.2 of [basic.life]/7.
The tempting answer is ok, assuming [=] copied v. Clang gives the warning implicit capture of 'this' with a capture default of '=' is deprecated, and ASan reports stack-use-after-scope.
Capturing the whole object by value (C++17) or copying just the member both make it defined:
struct X {
int v = 7;
auto get() { return [*this] { return v; }; }
};
int main() {
auto l = X{}.get();
return l(); // returns 7
}For the full treatment of lambda captures see Lambdas and closures.
What does this program print?
#include <cstdio>
#include <tuple>
int main() {
int i = 2;
std::tuple<int, int&> t{1, i};
auto [a, b] = t;
a = 10;
b = 20;
std::printf("%d %d\n", std::get<0>(t), i);
}- A.
10 20 - B.
1 20 - C.
1 2 - D.
10 2
Answer and explanation
Answer: B; it prints 1 20.
- With no ref-qualifier, [dcl.struct.bind]/1 introduces a hidden variable
eas if byauto e = t;.eis a copy oftand still has typestd::tuple<int, int&>: its first element is a newint, and its second element still refers toi. std::tupleis a tuple-like type, handled per [dcl.struct.bind]/7.eis not an lvalue reference, so it is passed togetas an xvalue.- Element 0: T₀ is
int,get<0>returnsint&&, and anint&& r0bound to the first element ofeis introduced.arefers to that object, soa = 10modifiese, nott. - Element 1: T₁ is
int&,get<1>returnsint&, an lvalue, and anint& r1bound toiis introduced.b = 20modifiesiitself.
- Element 0: T₀ is
- So
std::get<0>(t)is still 1, andibecomes 20.
A is wrong because it assumes the structured bindings bind directly to t; that would need auto& [a, b] = t;. C is wrong because it assumes copying severs the reference member from i, but copying a reference member yields a reference to the same object.
[dcl.struct.bind]/7 also says the referenced types of a and b are T₀ and T₁, so decltype(a) is int and decltype(b) is int&.
4. Constant evaluation and static initialization#
Judge this program.
#include <cstddef>
template <class T, std::size_t N>
constexpr std::size_t count(const T (&)[N]) { return N; }
void f(const int (&arr)[3]) {
static_assert(count(arr) == 3);
}
int main() {}Answer and explanation
Answer: well-formed.
arris a function parameter; the object it refers to lies outside the constant evaluation and cannot be used in constant expressions. In C++20 and earlier, the mere appearance of such a reference in a constant expression made it non-constant, and this code was rejected.- C++23 changed this through P2280R4. [expr.const.core]/9: during constant evaluation, a reference whose lifetime did not begin within the evaluation is treated as bound to an unspecified object whose lifetime spans the entire evaluation.
countonly bindsarrto its own parameter and returnsN, deduced from the type; it never reads an element's value, so it does not trigger the lvalue-to-rvalue conversion forbidden by [expr.const.core]/2.10. Socount(arr)is a constant expression.
The standard gives the same pattern in example 7 of [expr.const.core]/9 (use_array). Clang 23 accepts it.
As soon as a value is actually read, it fails. Both places below are rejected: the first performs an lvalue-to-rvalue conversion on an object not usable in constant expressions; the second reads the value of the non-constexpr pointer variable p.
#include <cstddef>
template <class T, std::size_t N>
constexpr std::size_t count(const T (&)[N]) { return N; }
void f(const int (&arr)[3]) {
static_assert(arr[0] == 0); // error: reads arr[0]
}
void g(const int (&arr)[3]) {
const int (*p)[3] = &arr;
static_assert(count(*p) == 3); // error: reads p
}Judge this program.
constexpr int f(int x) {
[[assume(x > 0)]];
return x;
}
constexpr int v = f(-1);
int main() { return v; }Answer and explanation
Answer: implementation-defined behavior. Whether the program is well-formed is up to the implementation.
- [dcl.attr.assume]/1: if the assumed expression would not evaluate to true, evaluating the assumption has runtime-undefined behavior.
- [intro.defs] defines the term: outside constant evaluation it is undefined behavior; during constant evaluation, whether the expression is thereby considered non-constant is implementation-defined, and it has no other effect.
- [expr.const.core]/3 says the same thing: if an expression satisfies the constraints of a core constant expression but its evaluation has runtime-undefined behavior, it is implementation-defined whether it is a core constant expression.
- If the implementation considers
f(-1)not a constant expression,vcannot be constant-initialized and is ill-formed per [dcl.constexpr]/6; if it does consider it constant,vhas the value -1 and the program is well-formed.
Clang 23 chooses the former and reports assumption evaluated to false. Choosing error because the compiler reports an error ignores the other, equally conforming, implementation.
Constant evaluation treats three kinds of undefined operations differently:
| Source of the undefined operation | Core constant expression? | Clause |
|---|---|---|
UB in the language clauses (4 through 15), such as x / 0 |
never; must be diagnosed | [expr.const.core]/2.8 |
| runtime-undefined behavior, such as a failed assumption | implementation-defined | [expr.const.core]/3 |
| UB specified in the library clauses | unspecified | [expr.const.core]/4 |
Which of the four function definitions labeled A through D makes the program ill-formed?
consteval int id(int x) { return x; }
template <class T>
constexpr int a(T t) { return id(t); } // A
static_assert(a(3) == 3);
constexpr int b(int t) { return id(t); } // B
auto c = [](int t) { return id(t); }; // C
static_assert(c(3) == 3);
constexpr int d(int t) { // D
if consteval { return id(t); }
return t;
}- A.
a - B.
b - C.
c - D.
d
Answer and explanation
Answer: B.
- In all four, the argument of
id(t)is a function parameter whose value is unknown, soid(t)is not a constant expression. - An
id(t)not in an immediate function context is an immediate invocation ([expr.const.imm]/1). An immediate invocation that is not a constant expression is an immediate-escalating expression (item 2.2 of [expr.const.imm]/2). - The last sentence of [expr.const.imm]/3: an immediate-escalating expression shall appear only in an immediate-escalating function. There are three kinds of immediate-escalating function: the call operator of a lambda not declared
consteval, a defaulted function that is not user-provided, and a function instantiated from a templated entity declaredconstexpr. An immediate-escalating function containing such an expression becomes an immediate function itself (item 4.2 of [expr.const.imm]/4).
Item by item:
- A:
a<int>is instantiated from a function template, so it is an immediate-escalating function and escalates to an immediate function. The condition ofstatic_assertis manifestly constant-evaluated and is in an immediate function context, soa(3)is fine. - B:
bis an ordinary non-templateconstexprfunction, not an immediate-escalating function, soid(t)appearing in it is ill-formed. Clang reports call to consteval function 'id' is not a constant expression. - C: the lambda's call operator is an immediate-escalating function and escalates to an immediate function;
c(3)in thestatic_assertis constant. - D: the compound statement of
if constevalis an immediate function context (item 1.3 of [expr.const.imm]/1), so theid(t)in it is not an immediate invocation.dremains an ordinaryconstexprfunction that can also be called at run time.
These immediate-escalation rules come from C++23's P2564R3. Escalation propagates outward along the call chain: in A, if main contained int n = 1; a(n);, then a<int> is already an immediate function, a(n) is an immediate invocation that is not a constant expression, and main is not an immediate-escalating function, so the error is reported at the call. Clang's note is 'a
Judge this program.
#include <cstddef>
#include <vector>
constexpr std::size_t n = std::vector{1, 2, 3}.size();
constexpr std::vector<int> v{1, 2, 3};
int main() { return n + v.size(); }Answer and explanation
Answer: ill-formed; the problem is v.
- Dynamic allocation is allowed at compile time, but it must be transient: [expr.const.core]/2.22 says that a call to
std::allocator<T>::allocatemakes the evaluation E not a core constant expression unless the allocated storage is deallocated within that same evaluation E.newexpressions have the corresponding [expr.const.core]/2.20. - In the initializer of
n, the temporaryvectoris destroyed at the end of the full-expression, and the memory it allocated is freed within this evaluation, sonis fine. - When the initialization of
vcompletes, its memory has not been freed; the allocation would have to persist into run time. The initializer is not a constant expression, and aconstexprvariable must be constant-initializable ([dcl.constexpr]/6), so it is ill-formed.
Clang 23's note is pointer to subobject of heap-allocated object is not a constant expression, pointing out that the allocation happened in allocator.h.
Compile-time dynamic allocation was introduced by C++20's P0784R7. It is easy to assume that since all of std::vector's member functions are constexpr, a constexpr std::vector variable can exist. When a result needs to survive into run time, compute the size at compile time and then copy into a std::array. On libc++, an empty constexpr std::vector<int> v{}; compiles, because default construction does not allocate.
What does this program print?
#include <cstdio>
#include <type_traits>
constexpr int f() {
if constexpr (std::is_constant_evaluated()) return 1;
else return 2;
}
constexpr int g() {
if (std::is_constant_evaluated()) return 1;
return 2;
}
int main() {
int a = f();
int b = g();
const int c = g();
std::printf("%d %d %d\n", a, b, c);
}- A.
1 2 1 - B.
1 2 2 - C.
2 2 1 - D.
1 1 1
Answer and explanation
Answer: A; it prints 1 2 1.
std::is_constant_evaluated() is equivalent to if consteval { return true; } else { return false; } ([meta.const.eval]/1), and if consteval takes the first branch only in a manifestly constant-evaluated context ([stmt.if]/5). So for each call site we need to decide whether it is manifestly constant-evaluated.
a: thestd::is_constant_evaluated()infis the condition ofif constexpr, which is itself manifestly constant-evaluated ([expr.const.defns]/1.2) and so always true.fis compiled to unconditionally return 1, regardless of the call site. Clang warns on this line: 'std::is_constant_evaluated' will always evaluate to 'true' in a manifestly constant-evaluated expression.b:int bis notconst, so it is not a potentially-constant variable ([expr.const.init]/6) and cannot be used in constant expressions; it has automatic storage duration, so constant initialization does not come into it either ([basic.start.static]/2 covers only static and thread storage duration). None of the conditions of [expr.const.defns]/1.6 hold,g()is evaluated at run time, and it returns 2.c: aconst intis a potentially-constant variable. When deciding whether it can be constant-initialized,std::is_constant_evaluated()is taken to be true (note 1 in [expr.const.init]/4);g()returns 1 and is a constant expression, socis constant-initialized and usable in constant expressions ([expr.const.init]/7). Hence its initializer is manifestly constant-evaluated ([expr.const.defns]/1.6), and its value is 1.
Example 1 in [expr.const.defns]/1 has the same contrast: in const int n = std::is_constant_evaluated() ? 13 : 17;, n is 13, while a non-const variable m written the same way may be 13 or 17. In our tests both -O0 and -O2 print 1 2 1.
To branch between compile time and run time, write if consteval directly since C++23; then you cannot accidentally write if constexpr.
The two translation units are linked together. (1) According to the standard, what is the value of copy? (2) Give two modifications that make copy always "hello, world", and justify them.
#include <string>
std::string make_greeting() { return "hello, world"; }
std::string greeting = make_greeting();#include <string>
extern std::string greeting;
std::string copy = greeting;
int main() { return copy.size(); }Answer and explanation
Answer: (1) the order of the two dynamic initializations is unspecified; if copy is initialized first, the behavior is undefined. (2) See below: for example, switch to constant initialization, use a function-local static, or use an inline variable in a header.
(1) Analysis:
make_greetingis notconstexpr, sogreetingcannot be constant-initialized; it is zero-initialized first and then dynamically initialized ([basic.start.static]/2).copyis dynamically initialized too.- Neither is an inline variable or a template specialization, so both have ordered initialization ([basic.start.dynamic]/1). But they are in different translation units, so there is no appearance order between them ([basic.start.dynamic]/2). If the program starts no other threads, by item 3.3 of [basic.start.dynamic]/3 the two initializations are indeterminately sequenced. In addition, whether initialization is deferred until after
mainstarts is implementation-defined ([basic.start.dynamic]/5). - If
greetingis initialized first,copygets"hello, world". Ifcopyis initialized first,std::string's copy constructor reads an object whose constructor has not run and whose lifetime has not begun, which is UB per [basic.life]/8. - The implementation executes one of the possible executions ([intro.abstract]/6), so the result cannot be relied on. In our tests, linking in the order
a.cpp b.cppreturns 12, and in the orderb.cpp a.cppreturns 0.
(2) Fixes; pick any two:
- Switch to constant initialization: for example, declare
constexpr std::string_view greeting = "hello, world";in a header and changeb.cppto direct-initializestd::string copy(greeting);(thestd::stringconstructor fromstring_viewisexplicit, so the original= greetingform does not compile). Constant initialization is static initialization and strongly happens before any dynamic initialization ([basic.start.static]/2). To keep a mutable global, writeconstinit: if the initialization is not constant initialization, the program is ill-formed ([dcl.constinit]/2), so the problem surfaces at compile time. That requires the initializer to be a constant expression, somake_greeting()must becomeconstexpr. Forstd::string, whether this works also depends on whether the standard library allocates during constant evaluation: if allocated memory is not freed within the initialization, the initializer is not a constant expression ([expr.const.core]/2.22). - Use a function-local static:
const std::string& greeting() { static const std::string s = make_greeting(); return s; }. A block-scope static variable is initialized the first time control passes through its declaration ([stmt.dcl]/3), socopy = greeting()always reads an initialized object. - Use an inline variable: write
inline std::string greeting = make_greeting();in a header and include it inb.cppbefore the definition ofcopy.greetinghas partially-ordered initialization, and every definition ofcopyis preceded by a definition ofgreeting, so by item 3.1 of [basic.start.dynamic]/3, in a single-threaded program the initialization ofgreetingcomes before that ofcopy. In our tests it returns 12 with both link orders.
This problem is usually called the static initialization order fiasco; for more background see [basic.start] and Every form of initialization.
Clauses at a glance#
| No. | Topic | Clauses |
|---|---|---|
| 1 | Right-before-left in assignment; i = i++ + 1 |
[intro.execution]/10, [expr.assign]/1 |
| 2 | Arguments are indeterminately sequenced | [expr.call]/8, [intro.execution]/8 |
| 3 | Unsequenced versus indeterminately sequenced | [intro.execution]/10, [expr.comma]/1, [expr.call]/8 |
| 4 | Lexical order in constant evaluation | [intro.execution]/16, [expr.const.core]/2.8 |
| 5 | Evaluation order of a chain of compound assignments | [expr.assign]/1, [expr.assign]/6 |
| 6 | Integral promotions and the usual arithmetic conversions | [conv.prom]/2, [expr.arith.conv]/1.5, [conv.integral]/3 |
| 7 | Signed overflow after promotion | [conv.prom]/2, [expr.pre]/4 |
| 8 | Width limits of shifts and C++20 semantics | [expr.shift]/1, [expr.shift]/2, [expr.shift]/3 |
| 9 | INT_MIN % -1 |
[expr.mul]/4 |
| 10 | Out-of-range floating-point to unsigned conversion | [conv.fpint]/1 |
| 11 | The range of an enumeration | [dcl.enum]/8, [expr.static.cast]/8 |
| 12 | Arithmetic between different enumerations | [expr.arith.conv]/1.3 |
| 13 | The signedness of char |
[basic.fundamental]/7, [conv.integral]/3 |
| 14 | Relational and equality comparison of pointers | [expr.rel]/4, [expr.rel]/5, [expr.eq]/4, [expr.const.core]/2.28 |
| 15 | Value categories of the conditional and comma operators | [expr.cond]/2, [expr.cond]/5, [expr.cond]/6, [expr.comma]/1 |
| 16 | A closure with a capture-default has no default constructor | [expr.prim.lambda.closure]/17, [expr.prim.lambda.capture]/7 |
| 17 | A bit-field structured binding cannot be captured by reference | [dcl.struct.bind]/8, [expr.prim.lambda.capture]/12 |
| 18 | [=] implicitly captures this by reference |
[expr.prim.lambda.capture]/10, [depr.capture.this]/1, [basic.life]/7 |
| 19 | What tuple-like structured bindings bind to | [dcl.struct.bind]/1, [dcl.struct.bind]/7 |
| 20 | Unknown references in constant evaluation | [expr.const.core]/9, [expr.const.core]/2.10 |
| 21 | Runtime-undefined behavior and constant evaluation | [dcl.attr.assume]/1, [expr.const.core]/3 |
| 22 | Immediate invocations and immediate-escalating functions | [expr.const.imm]/1, [expr.const.imm]/2, [expr.const.imm]/3, [expr.const.imm]/4 |
| 23 | Compile-time dynamic allocation must be transient | [expr.const.core]/2.22, [dcl.constexpr]/6 |
| 24 | std::is_constant_evaluated and manifest constant evaluation |
[expr.const.defns]/1, [expr.const.init]/7, [meta.const.eval]/1 |
| 25 | Dynamic initialization order across translation units | [basic.start.dynamic]/3, [basic.start.static]/2, [basic.life]/8 |