Function with no return type specified in C
I came across this piece of code in C:
#include <stdio.h>
main( )
{
int i = 5;
workover(i);
printf("%d",i);
}
workover(i)
int i;
{
i = i*i;
return(i);
}
I want to know how is it allowed to declare a function "overhaul"? What happens when we don't mention the return type of a function? (can we return anything?). The parameter is also just a variable name, how does it work?
source to share
If you don't specify a return type or a parameter type, C will implicitly declare it as int
.
This is a "feature" from earlier versions of C (C89 and C90) but is currently considered bad practice. Since the C99 (1999) standard no longer allows this, a compiler targeting C99 or later will likely give you a warning similar to the following:
program.c: At top level:
program.c:8:1: warning: return type defaults to βintβ
workover(i)
^
source to share
When I compile your code as $ gcc common.c -o common.exe -Wall
(Trying it through Cygwin terminal as I don't have my Linux system right now)
I am getting the following warnings:
common.c:3:1: warning: return type defaults to βintβ [-Wreturn-type]
main( )
^
common.c: In function βmainβ:
common.c:6:2: warning: implicit declaration of function βworkoverβ [-Wimplicit-f unction-declaration]
workover(i);
^
common.c: At top level:
common.c:9:1: warning: return type defaults to βintβ [-Wreturn-type]
workover(i)
^
common.c: In function βmainβ:
common.c:8:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
- The first and third say:
return type defaults to βintβ
which means that if you don't specify the return type, the compiler will implicitly declare it asint
. - The second says,
implicit declaration of function βworkoverβ
since the compiler doesn't know what it isworkover
. - The third warning is pretty easy to understand and will go away if you fix the first.
You should do it like this:
#include <stdio.h>
int workover(int);
int i;
int main(void)
{
int i = 5;
workover(i);
printf("%d",i); //prints 5
return 0;
}
int workover(int i)
{
i = i*i; //i will have local scope, so after this execution i will be 25;
return(i); //returns 25
}
source to share