Cover Image for Difference between Declaration of User Defined Function Inside main() and Outside of main() in C++
141 views

Difference between Declaration of User Defined Function Inside main() and Outside of main() in C++

The C++ declaration and definition of user-defined functions can occur both inside and outside of the main() function. However, there are significant differences between these two approaches.

  1. Inside main() (Local Function):
  • When you declare and define a function inside the main() function, it becomes a local function, visible only within the scope of the main() function.
  • It cannot be called from other functions or parts of the program outside the main() function.
  • This approach is suitable for small, simple programs or when you need a function for a specific purpose within main().
C++
 #include <iostream>

 int main() {
     void localFunction() {  // Declaration and definition inside main
         std::cout << "This is a local function." << std::endl;
     }

     localFunction();  // Call the local function

     return 0;
 }
  1. Outside main() (Global Function):
  • When you declare and define a function outside of the main() function (usually before main()), it becomes a global function, accessible from anywhere in the program.
  • It can be called not only from main() but also from other functions and parts of the program.
  • This approach is preferred for larger programs or when you need to reuse the same function in multiple places.
C++
 #include <iostream>

 // Declaration of a global function
 void globalFunction() {
     std::cout << "This is a global function." << std::endl;
 }

 int main() {
     globalFunction();  // Call the global function

     return 0;
 }

In general, it’s a good practice to define functions outside of main() when you want to create reusable code that can be called from multiple locations within your program. However, for very small and simple programs where a function is only needed within the main() function and nowhere else, you can declare and define it inside main(). Keep in mind that organizing your code with well-defined functions is often considered good programming practice as it enhances readability, maintainability, and reusability.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS