What is int main in C++

beginner c++11

Every C++ program starts with the main function. main returns int as a signal to other programs if your program was successful or not. By convention, programs return 0 when everything is ok and not 0 when something went wrong.

int main() {
  return 0; // success!
}



A Different Main

The main function in C++ can take different forms. To accept command line arguments you define a main with two parameters: how many arguments there are (“arg count”) and the arguments themselves (“arg vector”). If there are arguments, then the first one represents the program’s name.

#include <iostream>

int main(int argc, char** argv) {
  if (argc > 0) {
    std::cout << "Hello from " << argv[0] << "\n";
  }
  return 0;
}
Hello from ./how_to_start2

Main is Special

Main is the only function in C++ where it is not required to explicitly return a value. It is defined by the language that main returns 0 if the progam does not specify a return value.

int main() {
}




For more C++ By Example, click here.