Difference between declaration of user defined function inside main() and outside of main()
The declaration of a user-defined function inside the main() function and outside main() is similar to the declaration of local and global variables, i.e. When we declare a function inside the main, it is in local scope to main() and that function can be used in main() and any function outside main() can’t access the function which is local to main().
The function which is declared outside the main( ), which is a global declaration, can be accessed by any function outside and inside the main() function.
Let us see what differences occur by the declaration of function inside and outside the main() :
1. Outside main() (Global scope) –
When a sum() function is declared outside the main(), it is given global access, so sum() and caller() are functions in global scope when the caller() calls a sum() function it can access and no error occurs.
The sum is 10
2. Inside main() (Local Scope) –
When a sum() function is declared inside main(), it is local to main() and no functions outside the main() cannot access, so when the main() function calls caller() function, which is global, and when the caller() function calls sum() function, which is local to main() the caller() function cannot access the sum() function and thus we get error that “‘sum’ was not declared in this scope”
It gives error because the sum is local to main()
NOTE – The errors in the code are made to know what problem occurs with the function declaration inside the main()
But there some ambiguous cases occur. If we declare functions with the same name inside and outside the main, they are: Suppose if we declare a function with arguments outside the main and a function without arguments inside the main() with the same name, then if we call the function with the same name with arguments, the local function without arguments gets invoked and we get the error of insufficient arguments since the global one declared outside the main() function got ignored.
Let us see the example of the above in the code:
Simple declaration –
This doesn’t cause any ambiguity because the function local to main() itself accepts 2 arguments and hence, when we call the function, the function gets invoked.
When a function with the same name but a local one without arguments and a global one with arguments.
Error occurs since function sum() which is local to main() has two arguments
In this case, we get an error of insufficient arguments because the function in main() only gets considered and which takes two arguments, but still, there is a required function with no arguments declared globally but it was ignored.
Attention reader! Don’t stop learning now. Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.
Learn all GATE CS concepts with Free Live Classes on our youtube channel.