The 𝒎𝒂𝒊𝒏 function is the entry point to a program (in hosted environments) that can have one of the following forms:
𝒊𝒏𝒕 𝒎𝒂𝒊𝒏() { }
𝒊𝒏𝒕 𝒎𝒂𝒊𝒏(𝒊𝒏𝒕 𝒂𝒓𝒈𝒄, 𝒄𝒉𝒂𝒓* 𝒂𝒓𝒈𝒗[]) { }
With a common extension (part of POSIX) that includes environment variables:
𝒊𝒏𝒕 𝒎𝒂𝒊𝒏(𝒊𝒏𝒕 𝒂𝒓𝒈𝒄, 𝒄𝒉𝒂𝒓* 𝒂𝒓𝒈𝒗[], 𝒄𝒉𝒂𝒓* 𝒆𝒏𝒗𝒑[]) { }
Compiler Explorer link: https://compiler-explorer.com/z/vPP6oY5bx
𝒂𝒓𝒈𝒄 represents the number of program arguments, 𝒂𝒓𝒈𝒗 is an array of null-terminated strings representing the arguments. If 𝒂𝒓𝒈𝒗[0] is not null, it has to be the name used to invoke the program itself (or an empty string). 𝒂𝒓𝒈𝒗[𝒂𝒓𝒈𝒄] is guaranteed to be null.
The 𝒎𝒂𝒊𝒏 function has an implicit 𝒓𝒆𝒕𝒖𝒓𝒏 0, meaning that, unlike other functions, the return can be omitted. Additionally, after exiting the function body using 𝒓𝒆𝒕𝒖𝒓𝒏 𝒗, the equivalent of 𝒔𝒕𝒅::𝒆𝒙𝒊𝒕(v) is also executed.
Note that because the exit is evaluated after exiting the function body, a function try-catch block will not catch exceptions thrown during the destruction of static objects.
Finally, despite being a function, the 𝒎𝒂𝒊𝒏 is additionally constrained:
- 𝒎𝒂𝒊𝒏 cannot be named, meaning we can't take the address of 𝒎𝒂𝒊𝒏, can't call 𝒎𝒂𝒊𝒏 recursively or query the type of 𝒎𝒂𝒊𝒏
- the name "main" cannot be used for other functions in the global namespace or anything with C-linkage
- 𝒎𝒂𝒊𝒏 cannot be deleted, constexpr, consteval, inline or static, cannot have a deduced return type or be a coroutine