main() function defined without return type gives warning

后端 未结 5 574
春和景丽
春和景丽 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:14

    c automatically implies the datatype int to functions with no declared datatype. So as far as the compiler is concerned the above is:

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

    This expects that you would return an integer at the end of it with a return statement. If you explicitly specify it as void main() you are telling the compiler that the function does not have a return value, hence no warning.

    The reason that this is not an error is that if not specified, main() will return 0; at the end of execution. However the compiler is still giving you a warning that this is happening.

    Best practice is to use int main() and then return 0 at the end of your program execution like this.

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

    See: this question for more information.

提交回复
热议问题