简体   繁体   中英

Hello world program gives an error on void in main

I have typed in the following code in Ubuntu using Emacs and compiled using the command line

#include <stdio.h>

int main(void)
{
  printf("Hello World!\n\n");
  return 0;
}

Having the void in the main function argument returns the following warning

helloworld.c: In function ‘main’:
helloworld.c:6:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

When I removed the "void" within the parenthesis the program compiled without any errors. What is incorrect in have main(void) in this program?

Compilation command is gcc -Wall -ggdb helloworld.c -o hello

Edit: This is the screenshot which I would like to share在此处输入图片说明

The error doesn't have anything to do with the void in the signature of main() int main(void) is correct and is the way to define main() when you don't need to handle command line arguments.

The error means that you defined int main(void) and you did not return a value from the function. Like this

#include <stdio.h>

int main(void) 
{
    printf("Hello World!\n");    
}

This warning was removed for main() in newer versions of gcc because main() implicitly returns 0 when the program exits unless you indicate otherwise with exit() or an explict return from main() .

Normal functions still trigger this warning and it helps in prevention of undefined behavior due to not returning from a function and trying to capture the return value.

The only way that warning could be for main() function is if you don't have a return statement and you are compiling in C89/C90 mode.

Since C99, a return statement at the end of main() is not required and it'll be assumed to return 0; if control returns from main() 's end. So compile in c99 or C11 mode:

gcc -Wall -ggdb -std=c11 helloworld.c -o hello

which won't trigger that warning. Or make sure you have return statement if you are compiling in c89/C90. Until recently (at least upto gcc 4.9), the default mode in gcc is gnu90 . So you would get that warning withot a return statement if you don't pass std= .

I presume you don't actually have return 0; in your real code that produces this warning as it wouldn't matter in what mode of C you are compiling it if you had an explicit return statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM