Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What happens when a function is called before its declaration in C?
In C programming, when a function is called before its declaration, the compiler makes an assumption about the function's return type. If no prototype is provided, the compiler assumes the function returns an int by default. This can lead to compilation errors if the actual function returns a different type.
Syntax
return_type function_name(parameters); // Function declaration/prototype
Example 1: Error with Non-Integer Return Type
When a function returns a type other than int but is called before declaration, it causes a type conflict −
#include <stdio.h>
int main() {
printf("The returned value: %c<br>", function());
return 0;
}
char function() {
return 'T'; // return T as character
}
[Error] conflicting types for 'function' [Note] previous implicit declaration of 'function' was here
Example 2: Working with Integer Return Type
When the function actually returns an int, it works because the compiler's assumption is correct −
#include <stdio.h>
int main() {
printf("The returned value: %d<br>", function());
return 0;
}
int function() {
return 86; // return an integer value
}
The returned value: 86
Example 3: Proper Solution with Function Prototype
The correct approach is to declare the function prototype before calling it −
#include <stdio.h>
char function(); // Function prototype
int main() {
printf("The returned value: %c<br>", function());
return 0;
}
char function() {
return 'T'; // return T as character
}
The returned value: T
Key Points
- The compiler assumes
intreturn type for undeclared functions - Type conflicts occur when actual return type differs from assumed
int - Function prototypes prevent such compilation errors
- Always declare function prototypes before using functions
Conclusion
Calling functions before declaration leads to implicit int assumptions by the compiler. To avoid type conflicts and ensure code correctness, always declare function prototypes before calling them.
