-5

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;
}
msc
  • 33,420
  • 29
  • 119
  • 214
  • "I don't understand, how main function call my own function. " - it doesn't - it's called before main and you print out the return value. –  Mar 08 '17 at 18:24
  • 3
    Silly stuff and complete misunderstanding needs to read [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – πάντα ῥεῖ Mar 08 '17 at 18:29

2 Answers2

8

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

As Some programmer dude explained, it is being called before the main function.

To not be confused, I suggest that you explicitly call the myFunc() in the main function:

#include <iostream>
using namespace std;

int myFunc();

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

int myFunc()
{
    int i = 10;
    int j = 20;
    return i+j;
}
KelvinS
  • 2,870
  • 8
  • 34
  • 67