constexpr issues of note
(Romeo/Khlebnikov/Meredith):
Compile time fail:
static_assert(sizeof(int) == 4);
constexpr int ub(int i) { return i*i; }
// cpp20 clang/gcc: runtime value: 0
const int ci(ub(1<<16)); std::cout << "ci=" << ci << '\n';
// cpp20 clang/gcc: compile error
constexpr const int cci(ub(1<<16)); std::cout << "cci=" << cci << '\n';
constinit const int cci(ub(1<<16));
// cpp20 clang/gcc: compile error
consteval int cub(int i) { return i*i; }
const int ci(cub(1<<16));
Kink quirks:
// --- common.hpp
#pragma once
/*
$ nm -C a.out | grep _c
36:0000000000002004 r _c
37:0000000000002008 r _c
38:000000000000200c r _c
*/
constexpr int _c = 42;
extern const int* func1();
extern const int* func2();
//--- file1.cpp
#include "common.hpp"
const int* func1() { return &_c; }
//--- file2.cpp
#include "common.hpp"
const int* func2() { return &_c; }
//--- link.cpp -std=c++20
#include "common.hpp"
#include <cassert>
#include <iostream>
int main()
{
const int* x1 = func1();
const int* x2 = func2();
assert( x1 != x2 ); // !! different addresses in memory
assert( *x1 == *x2 );
assert( *x1 == 42 );
return 0;
}
Written on April 11, 2025