Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do programs in C compile even when the return statement is missing? [duplicate]

Tags:

c

I'm implementing some basic data structures in C and I found out that if I omit the return type from a function and call that function the compiler doesn't generate an error. I compiled with cc file.c and didn't use -Wall (so I missed the warning) but in other programming languages this is a serious error and the program won't compile.

Per Graham Borland's request, here's a simple example:

int test() 
{
  printf("Hi!");
}

int main() 
{ 
    test();
}
like image 304
Daniel Avatar asked Jun 01 '12 23:06

Daniel


2 Answers

C is an old language and at the time it was introduced, returning integers was common enough to be the default return type of a function. People later started realizing that with more complicated return types, it was best to specify int to be sure you are not forgetting the return type, but in order to maintain backwards compatibility with old code, C could not remove this default behavior. Instead most compilers issue warnings.

If the function reaches the end without a return statement an undefined value is returned except in the main function, 0 is returned. This has the same reason as above.

/* implicit declaration of printf as: int printf(int); */

/* implicit int type */
main()
{
    printf("hello, world\n");
} /* implicit return 0; */
like image 60
Matt Avatar answered Oct 07 '22 09:10

Matt


It's because in C, any variable / function is implicitly int.

This is the same reason that you can use register instead of register int, or unsigned instead of unsigned int, auto instead of auto int, and static instead of static int. I personally always explicitly qualify my variables with int, but whether you do or not is your option.

like image 37
Richard J. Ross III Avatar answered Oct 07 '22 11:10

Richard J. Ross III