- 1

What is the purpose of declaring a function? Explain with example.

14th Jan 2017, 4:16 PM
Vaibhav kumar
Vaibhav kumar - avatar
2 odpowiedzi
+ 6
Declaring? Well, if you mean about for example: int sum(int x, int y) { return (x+y); } int in that function tells you the return type, it that case the function returns an integer.
14th Jan 2017, 6:16 PM
Filip
Filip - avatar
+ 1
Consider following example, int main () { int sum = add(a,b); cout << sum; return 0; } int add(int x, int y) { return x+y; } Now if you try to run this, you'll get an error something like, "error: 'add' was not declared in this scope" Why is that? Because compiler doesn't know yet what is 'add'. We need to tell this to our compiler. So we have two options to do that. First, reorder the functions: int add(int x, int y) { return x+y; } int main () { int sum = add(a,b); cout << sum; return 0; } You will see, this solves our error and our program executes correctly. Second, forward declaration: int add(int, int); int main () { int sum = add(a,b); cout << sum; return 0; } int add(int x, int y) { return x+y; } It is difficult to order the functions when our programs gets too big, you have to take care of which function calls which function. It is easier to use forward declaration to make your coding life simpler.
14th Jan 2017, 8:48 PM
Gurjot