user6258428
user6258428

Reputation: 19

How legal is this definition of `main`?

In a hosted system, the standard requires main be defined with a "declared return type of type int". The "declared" here appertains to "deduced return types" so we can ignore that word for the purposes of this question. In C, the standard explicitly has a footnote that says a typedef can be used for int but this is missing in the C++ standard. I'm going to assume the intent is the same as the language is "return type of type int" and "a function of () returning int" and a typedef is simply an alias, not a different type. Therefore this program would be considered legal:

typedef int boobs;
boobs main() { }

What if we do this instead?

#include <cstdint>

int32_t main() {}

On many systems this will compile as int32_t is just int but not all systems. My confusion stems from the fact that int32_t is an implementation-defined value, meaning compilation failure depends on the implementation.

So what's the legality of this situation? Is the entire program ill-formed because it can sometimes compile or not? Or is it well-formed because it depends on an implementation-defined value that comes from the standard library?

Upvotes: 0

Views: 312

Answers (1)

eerorika
eerorika

Reputation: 238331

The program is well formed if and only if int32_t is an alias (a typedef) of int.

Obviously, in systems that do not support int32_t (fixed width integers are optional), the use of non-declared int32_t is illegal.

Also, even if int32_t is supported by the compiler, it is not required to declare it in the global namespace in the header <cstdint> (only std::int32_t is guaranteed), so the program relies on that aspect of the implementation.

Also, in systems where int32_t is another type distinct from int, the program will be ill formed.

So, it is implementantion defined, whether the program is well formed or not. On some systems it is; on others it's not. To put it even more concisely, the program is conditionally well formed.

Upvotes: 4

Related Questions