0
0
C++programming~5 mins

main function and program entry in C++

Choose your learning style9 modes available
Introduction

The main function is where a C++ program starts running. It tells the computer what to do first.

When you want to create a program that runs from start to finish.
When you need a place to begin your instructions for the computer.
When you want to control the flow of your program from a single point.
When you want to return a status code to the system after your program finishes.
Syntax
C++
int main() {
    // your code here
    return 0;
}

The int before main means the function returns a number to the system.

return 0; means the program finished successfully.

Examples
Simple main function that ends immediately and tells the system everything is okay.
C++
int main() {
    return 0;
}
Main function that prints a message before ending.
C++
#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}
Main function that can receive information from the command line.
C++
int main(int argc, char* argv[]) {
    // argc counts arguments, argv holds them
    return 0;
}
Sample Program

This program starts at main, prints a welcome message, then ends successfully.

C++
#include <iostream>

int main() {
    std::cout << "Welcome to my program!" << std::endl;
    return 0;
}
OutputSuccess
Important Notes

Every C++ program must have exactly one main function.

The main function can return other numbers to signal different results.

Using return 0; means the program ran without errors.

Summary

The main function is the starting point of a C++ program.

It usually returns an integer to tell the system if the program ended well.

Inside main, you write the instructions your program will follow.