Supriyo
Supriyo

Reputation: 107

Calling functions from main() in c++

I came across a program with 10 header and 10 source files. I read in my text book that the functions are called from main. But how can I pass data to so many functions from main()?

Upvotes: 1

Views: 8535

Answers (2)

M. Williams
M. Williams

Reputation: 4985

To my mind, this phrase isn't correct, but I guess what was meant to be said could be rephrased like "Every function or class method that you implement and use would be somehow called from your main() routine"

And somehow in this context would actually mean directly or indirectly - via other functions / function wrappers.

Anyway, the idea should be clear - any significant action that is done in your application is actually done using some function call from your main() routine, which is sometimes also called application root (try to think of your application as a tree of function calls and then your main() function would be right in the top of your tree).

Upvotes: 2

Emile Cormier
Emile Cormier

Reputation: 29209

Functions don't necessarily need to called from main. They can be called by other functions. For example:

int foo(int x)
{
    return x*x;
}

int bar(int x)
{
   return foo(x) + 1;
}

int main()
{
    int a = bar(42);
    std::cout << a << std::endl;
    return 0;
}

Note that foo() is never called directly from main().

Upvotes: 14

Related Questions