When you attempt to use constexpr with main like this:
constexpr int main()
gcc and clang complain:
error: cannot declare '::main' to be inline
error: 'main' is not allowed to be declared constexpr
Let's see what requirements for constexpr function are:
A constexpr function must satisfy the following requirements:
- it must not be virtual
- its return type must be LiteralType
- each of its parameters must be literal type
What is LiteralType?
A literal type is any of the following
- void(since c++14)
- scalar type
- reference type
- an array of literal type
What must the function body include?
- null statements
- static_assert declarations
- typedef declarations and alias declarations that do not define classes or enumerations
- using declarations
- using directives
- exactly one return statement that contains only literal values, constexpr variables and functions.
The following examples:
constexpr int main() { ; }
constexpr int main() { return 42; }
constexpr int main() {
// main defaults to return 0
}
seems to fit all these requirements. Also with that, main is special function that runs at start of program before everything else. You can run constexpr functions from main, and in order for something marked constexpr to be constexpr, it must be run in a constexpr context.
So why is main not allowed to be a constexpr?
forkandexecto just execute/bin/false? - Johannes Schaub - litb/bin/false! - xtofl