+ 1

Without declaration of a function how we can call or define a function? I think compiler should give an error but its not.

The examples given in this app does not declare function before main, but calling and defining it later. How? Confused. Please help Language:Cpp

7th Mar 2019, 8:33 AM
Rimsha Bibi
7 Réponses
+ 8
You can either declare a function first, then call it from main() and define it afterwards: // declaration int sum(int, int); int main() { // function call cout << sum(5, 4) << endl; return 0; } // function definition int sum(int a, int b) { return a+b; } OR you can define the whole function before main() (this is what your code does): // function definition int sum(int a, int b) { return a+b; } int main() { // function call cout << sum(5, 4) << endl; return 0; } Since you defined the function before main(), you don't need to declare it because the function is already "known" to the compiler when main() is executed. By declaring a function you tell the compiler that you'll be using a function in main() that isn't defined yet. So when the compiler finds the function call in main(), it knows that there will be a function definition somewhere in the code and it will look for it. Whereas if you do this: // no function declaration int main() { // function call cout << sum(5, 4) << endl; return 0; } // function definition int sum(int a, int b) { return a+b; } the code won't compile because you're trying to use a function sum() without declaring OR defining it first, so the compiler will have no idea what sum() means.
7th Mar 2019, 9:25 AM
Anna
Anna - avatar
+ 4
If you can show us your code there are plenty who can help.
7th Mar 2019, 8:55 AM
BroFar
BroFar - avatar
+ 3
You can't call a function without declaring it first.It's how it works in C++..
7th Mar 2019, 9:27 AM
Mensch
Mensch - avatar
+ 3
Thanks all :)
7th Mar 2019, 9:42 AM
Rimsha Bibi
+ 1
For example this code, there's no deceleration of function sum but still called and defined. How? Is it true that without declaration we cannot define or call a program? https://code.sololearn.com/cyB4L3rIlszA/?ref=app
7th Mar 2019, 9:21 AM
Rimsha Bibi
+ 1
BroFarOps©®️™️🐱 I was asking about all the examples given by this app. They aren't declaring function first. Still tysm as beginner. Next time I'll post code related questions with code.
7th Mar 2019, 9:25 AM
Rimsha Bibi
0
Anna your explanation on the function definition and declaration just saved my life. thank you so much
12th Sep 2022, 10:24 PM
bakare damilola
bakare damilola - avatar