Search code examples
c++program-entry-point

How main function call in C++


I have created function and call above the main() function. It is successfully call the function in GCC compiler on Linux platform. I don't understand, how main function call my own function.

#include <iostream>
using namespace std;

int myFunc();

int ret = myFunc();

int main()
{
    cout << ret << endl;
}

int myFunc()
{
    int i = 10, j = 20, k;
    k = i+j;
    return k;
}

Solution

  • Global variables are initialized before main is called. Therefore the call to myFunc happens before main is called. Your main function doesn't call myFunc at all.

    It would have been very obvious if you used a debugger and set breakpoints in the myFunc and main functions, and looking at the call stack.