main() function defined without return type gives warning

后端 未结 5 575
春和景丽
春和景丽 2020-12-11 12:24

This is my program:

main()
{ 
    printf(\"hello world\\n\");
}

I get this warning when compiling it:

function should retur         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 13:05

    You got the warning because you didn't specify the return type of main.

    You should always use int main, and return an int number, usually 0 for success.

    int main()
    { 
        printf("hello world\n");
        return 0;      //you can omit this since C99
    }
    

    Using void main on a hosted environment(normally we are, if not, the following doesn't have to be true) leads to undefined behavior, even though it works in some compilers, never use it.

    The standard says main has two kinds of prototype, both returns int:

    C11 5.1.2.2.1 Program startup

    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;10) or in some other implementation-defined manner.

提交回复
热议问题