Why main() function run first of all then other functions what if we want another function run first then main function in c or c++. Can anyone explain logic behind it.thanks.
-
3If you want another function to run first then call it at the start of `main()`. – Aug 31 '18 at 13:31
-
You have programming background in interpreted languages, don't you? With this information, answers could compare to concepts you are used to. – Yunnosch Aug 31 '18 at 13:56
-
In C++ isn't the constructor of global objects called before main? – Osiris Aug 31 '18 at 13:57
-
1@Osiris Yes it is. – NathanOliver Aug 31 '18 at 13:58
4 Answers
A program has to start somewhere... As far as the developer is concerned that's typically main()
- referred to as the "entry point".
If you want to do certain things at the beginning of your program, then just move the content of your main()
into another function (like run()
), and place the startup code in main()
before calling run()
.
#include <stdio.h>
void init(void) {
/* startup */
}
void run(void) {
/* application functionality */
}
int main(void) {
init();
run();
exit 0;
}
As far as the wider system is concerned there is an amount of setup that happens first:
- The process needs to be created (e.g:
fork()
) - The stack needs to be prepared
- Global variables need to be initialized
- etc...

- 6,690
- 2
- 24
- 34
Because that's what the Standard defines the language to use (C++ quoted here):
[basic.start.main]
A program shall contain a global function called
main
. Executing a program starts a main thread of execution (...) in which the main function is invoked (...)
So the compiler has to produce the binary in a way that calls main
when the program is started by the operating system, or, in case of freestanding environments, when it's loaded.
Technically speaking, it doesn't have to be the first call
in the resulting assembly. The compiler can insert some additional startup code (like initializing variables etc.), which can itself be grouped into functions. This is out of concern of a C++ program developer, but becomes quite important on embedded systems, where you need/want to be aware of almost every instruction executed.

- 1
- 1

- 38,596
- 7
- 91
- 135
This is because you can create any number of functions in a program. You can have 1 function, 10, 2340 functions, or whatever. The program needs to know where to start. This is the purpose of the main
function, as that is always the first function called.

- 455
- 2
- 5
- 12
You need to have a place in the program where the execution starts. In C it is function main.
But the program starts executing before the call to the main. That before main
code prepares the execution environment for your program and it is called
a startup code.

- 60,014
- 4
- 34
- 74