In the previous post, we discussed functions in detail and here in this post, we are going to discuss one error that we often encounter while working with functions which is the "implicit declaration of function".
The implicit declaration function error is encountered when you use (or call) the function before declaring or defining it. It is because the compiler has no information about that function at the time of calling it so the compiler implicitly assumes something about the function.
Example:
//C++ Implicit Declaration of function #include<iostream> using namespace std; int main(){ int m = 6, n = 8; //function call int greater = find(m, n); cout<<"Greater number is: "<<greater; return 0; } //function definition int find(int x, int y){ if(x < y){ return y; } else{ return x; } }
../src/main.c:48:9: error: implicit declaration of function 'find' [-Werror=implicit-function-declaration] find();
Here the find() function is not declared before calling inside the main function and the definition of the function is written after the main function so when it is called inside the main function the compiler has no information about the find() function and gives us an error message. (alert-warning)
How Execution takes place in C++?
How to resolve Implicit Declaration of Function Error?
- If you define the function before the main function then you only have to define it and you don't have to separately declare or define it.
//C++ Example program to find greater #include<iostream> using namespace std; //function definition before using it int find(int x, int y){ if(x < y){ return y; } else{ return x; } } int main(){ int m = 6, n = 8; //function call int greater = find(m, n); cout<<"Greater number is: "<<greater; return 0; }
Greater number is: 8
- If you define a function after the main function then you have to put a matching declaration of that function before the main.
//C++ Example program to find greater #include<iostream> using namespace std; //function declaration before using it int find(int, int); int main(){ int m = 6, n = 8; //function call int greater = find(m, n); cout<<"Greater number is: "<<greater; return 0; } //function definition after main int find(int x, int y){ if(x < y){ return y; } else{ return x; } }
Greater number is: 8
No comments:
Post a Comment