-2

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.

shoaib sabir
  • 605
  • 2
  • 9
  • 23

4 Answers4

4

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...
Attie
  • 6,690
  • 2
  • 24
  • 34
4

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.

Community
  • 1
  • 1
Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
0

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.

Keltari
  • 455
  • 2
  • 5
  • 12
0

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.

0___________
  • 60,014
  • 4
  • 34
  • 74