https://rentry.org/PPP2_p290

// 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

PrevUpNext

Edit
Pub: 04 Apr 2023 15:09 UTC
Edit: 03 May 2023 00:40 UTC
Views: 359