Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Is it undefined behavior to have main be anything other than a function that returns int?


Yes, in hosted environment it is UB, unless the implementation specifies otherwise. Relevant quotes from N1256:

1. In this International Standard, "shall" is to be interpreted as a requirement on an implementation or on a program;

2. If a "shall" or "shall not" requirement that appears outside of a constraint is violated, the behavior is undefined.

3. (5.1.2.2) A hosted environment need not be provided, but shall conform to the following specifications if present.

4. (5.1.2.2.1) The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }
or equivalent; or in some other implementation-defined manner.

5. (J.2 Undefined behavior) - A program in a hosted environment does not define a function named main using one of the specified forms (5.1.2.2.1).


UB comes with high-level languages. "main" is not specified in the high-level language, but by the OS. You write some machine code, give it the name "main" and the OS jumps to that location and starts executing. One should adhere to the "C calling convention" (managing the stack correctly) if that code is expected to behave within the system.

But "main is not a function" does not produce undefined behavior.


> "main" is not specified in the high-level language, but by the OS. You write some machine code, give it the name "main" and the OS jumps to that location

main() is specified by C. The OS as such doesn't know or care about main. Headers in the binary executable specify where the OS should begin execution, and this is rarely in main.


If you're feeding source code to a C compiler, it makes sense to ask whether or not it contains UB.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: