Introduction
A function is a collection of statements that work together to complete a task. Every C program includes at least one function, main(), and even the most simple programs can declare additional functions.
You may split your code into functions. It is up to you to split your code into various functions, but logically the separation should be such that each function performs a distinct task.
A function declaration informs the compiler about the function's name, return type, and parameters. A function definition provides the actual body of the function.
One question that might come to your mind regarding function is what happens if we call a function before its declaration. Well, don't worry today in this article we will be answering this question with detailed codes and explanations.
Also see: C Static Function, Tribonacci Series
What happens when a function is called before its declaration in C?
If we don't use any function prototypes, the function body is declared in a section that comes after the function's calling statement. The compiler believes the default return type is an integer in this situation. However, if the function returns a different type of value, it throws an error. If the return type is likewise an integer, it will operate correctly; however, certain warnings may be generated.
Example
The following program, for example, fails to compile.
#include <stdio.h>
int main(void)
{
// sampleFunc() is not declared
printf("%c\n", sampleFunc());
return 0;
}
char sampleFunc()
{
return 'C';
}
Output
error: 'sampleFunc' was not declared in this scope
40 | printf("%c\n", sampleFunc());
| ^~~~~~~~~~
If the function char sampleFunc() in the above code is declared after main() and the calling statement, it will fail to compile. Because the compiler, by default, believes the return type to be "int." And if the return type does not match int at the time of declaration, the compiler will throw an error.
Because the function is declared before the main, the following program compiles and runs correctly ().
#include <stdio.h>
int sampleFunc()
{
return 20;
}
int main(void)
{
//sampleFunc() is declared
printf("%d\n", sampleFunc());
return 0;
}
Output
20
You can also read about the jump statement and Short int in C Programming