How to declare a constant in C++
summary
C++ constants behave differently at compile time and runtime: prefer constexpr whenever possible because it enables compile-time folding and removes duplicate storage; local constants need static for static storage duration to avoid per-call construction and the guard is only paid once; header constants require inline to get one copy across translation units or use extern/definition in a .cpp; tools used include Compiler Explorer, assembly inspection, readelf and nm and -flto to remove duplicate init code; modules change linkage rules and can still hide ODR violations across module implementation units.
AI-written summary · about
chapters (23)
- 0:00Introduction
- 2:16Defining constants in C++
- 3:00Prefer constexpr over const
- 4:04Local constants optimization
- 6:11Local constants with static storage
- 9:29Non-literal local constants
- 13:09Global constants in CPP files
- 17:45Global constants with anonymous namespaces
- 18:06Global constants in headers
- 20:37Constexpr in headers
- 23:55Weak linkage with inline
- 25:44Non-literal types in headers
- 28:58Link time optimization
- 30:25Detaching declaration and definition with extern
- 33:36Static data members
- 35:05C++ modules intro
- 36:29Modules: Interface and implementation
- 39:19Modules linkage and constexpr
- 41:09ODR violations in modules
- 43:17Guidelines for module constants
- 45:47Constant compiler quirks
- 49:00Summary
- 49:43Q&A
related talks
05mLightning Talk: Detecting Constant Folding to Prevent Substitution Failure
01h 02mBack to Basics: const and constexpr
21mMisusing Const for Fn and Profit
01h 30mC++ in Constrained Environments
01h 02mEmbedded Friendly C++: Features That Make a Difference
59mCombining C++17 Features
23mFunctional Programming in C++ (Run time vs Compile time types)
01h 01mFreestanding C++ - Past, Present, and Future
