https://rentry.org/PPP2_p290 ⎗ ✓ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38// Code derived from Stroustrup's PPP2 book // § 8.5.9 constexpr functions // -and beginning on p 290 constexpr double xscale = 10; // scaling factors constexpr double yscale = 0.8; struct Point { double x; double y; }; constexpr Point scale(Point p) { return {xscale * p.x, yscale * p.y}; }; void user(Point p1) { Point p2{10, 10}; Point p3 = scale(p1); // OK: p3 == {100,8}; run-time evaluation is fine Point p4 = scale(p2); // p4 == {100,8} // error: scale (p1) is not a constant expression constexpr Point p5 = scale(p1); constexpr Point p6 = scale(p2); // p6 == {100,8} // . . . } int glob = 9; constexpr void bad(int& arg) // error: no return value { ++arg; // error: modifies caller through argument glob = 7; // error: modifies nonlocal variable } int main() {} build & run: g++ -std=c++20 -O2 -Wall -pedantic ./ch_08/main_p290.cpp && ./a.out sauce: Bjarne Stroustrup's PPP2 textbook /robowaifu/'s official C++ learning textbook thread Prev • Up • Next