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:
What is LiteralType?
A literal type is any of the following
What must the function body include?
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?
constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.
It means that compiler makes most general assumptions when compiling this function. And this assumption is that arguments are non-compile-time. It means that compiler can't guarantee that your if-constexpr is always compile-time, hence the error about it.
A static constexpr variable has to be set at compilation, because its lifetime is the the whole program. Without the static keyword, the compiler isn't bound to set the value at compilation, and could decide to set it later.
No, no such thing exists in C.
No, this is not allowed the draft C++ standard in section 3.6.1
Main function paragraph 3 says:
[...]A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed.[...]
main
has to be a run-time function and as Lightness says it makes no sense since you can't optimize main
away.
The standard gives the precise signature for main
, so the compiler is allowed to reject other signatures. Even more specifically, it prescribes that main
cannot be constexpr
, static
, or some other things.
If you're wondering why, the compiler is allowed to insert code at the beginning of main
(to do stuff like initialize global variables, etc.) which could make it non-constexpr
(which is why e.g. a program is not allowed to call main explicitly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With