Introduction #
Every C++ program must have a function named main().
This is not a C++ rule made for learners.
This is how the operating system runs a C++ program.
When you execute a compiled program, the OS looks for main() and starts running code from there. If main() is missing, the program will not run.
Basic form of main() #
int main()
{
return 0;
}
This is the simplest valid main() function. No matter how large your program becomes, execution always begins here.
Why main() returns int #
main() returns an integer because the program needs to report a result back to the operating system.
return 0;means the program finished successfully- Any non-zero value usually indicates some error
You may not use this information immediately, but it matters when:
- Your program is called from another program or script
- You work with build systems
- You deal with embedded or system-level programs
Because of this, main() returning int is not optional.
Writing code inside main() #
Anything written inside main() is executed when the program runs.
Example:
#include <iostream>
int main()
{
std::cout << "Program started";
return 0;
}
What happens here is simple:
- Program starts
- Code inside
main()runs line by line - Program exits after
return 0
That’s all.
return 0; should be written explicitly #
Some compilers allow you to skip return 0; in main().
Even so, writing it explicitly is a good habit. It makes your intention clear and avoids confusion later when code becomes larger or more complex.
Clear code is always easier to maintain.
main() with arguments #
You will eventually see main() written like this:
int main(int argc, char* argv[])
{
return 0;
}
For now, just know that:
argctells how many arguments were passedargvholds the argument values
This is used when running programs from the command line with inputs.
We’ll cover this properly in a separate topic.
Important rule #
There must be only one main() function in a C++ program.
If you define more than one:
- The compiler will give an error
- The program will not build
Other functions can be named anything.main() is special and must exist exactly once.
Final note #
C++ does not try to guess what you want.
It expects things to be written clearly and correctly.
Understanding main() early helps you avoid many beginner mistakes and makes compiler errors easier to understand later.