Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      Main function

      From cppreference.com
      <cpp‎ |language
       
       
      C++ language
      General topics
      Flow control
      Conditional execution statements
      Iteration statements (loops)
      Jump statements
      Functions
      Function declaration
      Lambda function expression
      inline specifier
      Dynamic exception specifications(until C++17*)
      noexcept specifier(C++11)
      Exceptions
      Namespaces
      Types
      Specifiers
      constexpr(C++11)
      consteval(C++20)
      constinit(C++20)
      Storage duration specifiers
      Initialization
      Expressions
      Alternative representations
      Literals
      Boolean -Integer -Floating-point
      Character -String -nullptr(C++11)
      User-defined(C++11)
      Utilities
      Attributes(C++11)
      Types
      typedef declaration
      Type alias declaration(C++11)
      Casts
      Memory allocation
      Classes
      Class-specific function properties
      Special member functions
      Templates
      Miscellaneous
       
       

      A program shall contain a global namespace function namedmain, which is the designated start of the program in hosted environment. It shall have one of the following forms:

      int main() {body} (1)
      int main(intargc,char*argv[]) {body} (2)
      int main(/* implementation-defined */) {body} (3)
      1) Amain function running independently of environment-provided arguments.
      2) Amain function accepting environment-provided arguments.
      The names ofargc andargv are arbitrary, as well as the representation of the types of the parameters:int main(int ac,char** av) is equally valid.
      3) Amain function of implement-defined type, returningint.
      The C++ standard recommends implementation-definedmain functions to place the extra (optional) parameters afterargv.
      argc - Non-negative value representing the number of arguments passed to the program from the environment in which the program is run.
      argv - Pointer to the first element of an array ofargc+1 pointers, of which the last one is null and the previous ones, if any, point tonull-terminated multibyte strings that represent the arguments passed to the program from the execution environment. Ifargv[0] is not a null pointer (or, equivalently, ifargc>0), it points to a string that represents the name used to invoke the program, or to an empty string.
      body - The body of themain function.

      Contents

      [edit]Explanation

      Themain function is called at program startup afterinitialization of the non-local objects with staticstorage duration. It is the designated entry point to a program that is executed inhosted environment (that is, with an operating system). The entry points tofreestanding programs (boot loaders, OS kernels, etc) are implementation-defined.

      The parameters of the two-parameter form of themain function allow arbitrary multibyte character strings to be passed from the execution environment (these are typically known ascommand line arguments), the pointers[argv[1]argv[argc-1]] point at the first characters in each of these strings.argv[0] (if non-null) is the pointer to the initial character of a null-terminated multibyte string that represents the name used to invoke the program itself (or an empty string"" if this is not supported by the execution environment). The strings are modifiable, although these modifications do not propagate back to the execution environment: they can be used, for example, withstd::strtok. The size of the array pointed to byargv is at leastargc+1, and the last element,argv[argc], is guaranteed to be a null pointer.

      Themain function has the following several special properties:

      1) The body of themain function does not need to contain thereturn statement: if control reaches the end ofmain without encountering a return statement, the effect is that of executingreturn0;.
      2) Execution of the return (or the implicit return upon reaching the end ofmain) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration and evaluates anypostcondition assertions ofmain(since C++26)) and then callingstd::exit with the same argument as the argument of thereturn (std::exit then destroys static objects and terminates the program).

      Themain function has several restrictions (violation of which renders the program ill-formed):

      1) It cannot benamed anywhere in the program
      a) in particular, it cannot be called recursively
      b) its address cannot be taken
      c) it cannot be used in atypeid expressionor adecltype specifier(since C++11)
      2) It cannot be predefined and cannot be overloaded: effectively, the namemain in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that an entity namedmain cannot be declared with Clanguage linkage in any namespace).
      3) It cannot bedefined as deleted or(since C++11) declared with any language linkage,constexpr(since C++11),consteval(since C++20),inline, orstatic.
      4) The return type of themain function cannot be deduced (auto main(){...} is not allowed).
      (since C++14)
      5) Themain function cannot be acoroutine.
      6) Themain function cannot attach to a namedmodule.
      (since C++20)

      [edit]Notes

      If themain function is defined with afunctiontry block, the exceptions thrown by the destructors of static objects (which are destroyed by the impliedstd::exit) are notcaught by it.

      The manner in which the arguments given at the OS command line are converted into the multibyte character arrays referenced byargv may involve implementation-defined processing:

      A very common implementation-defined form ofmain() has a third argument (in addition toargc andargv), of typechar**, pointing atan array of pointers to the execution environment variables.

      [edit]Example

      Demonstrates how to inform a program about where to find its input and where to write its results.
      A possible invocation:./convert table_in.dat table_out.dat

      Run this code
      #include <cstdlib>#include <iomanip>#include <iostream> int main(int argc,char*argv[]){std::cout<<"argc == "<< argc<<'\n'; for(int ndx{}; ndx!= argc;++ndx)std::cout<<"argv["<< ndx<<"] == "<<std::quoted(argv[ndx])<<'\n';std::cout<<"argv["<< argc<<"] == "<<static_cast<void*>(argv[argc])<<'\n'; /* ... */ return argc==3?EXIT_SUCCESS:EXIT_FAILURE;// optional return value}

      Possible output:

      argc == 3argv[0] == "./convert"argv[1] == "table_in.dat"argv[2] == "table_out.dat"argv[3] == 0

      [edit]References

      Extended content
      • C++23 standard (ISO/IEC 14882:2024):
      • 6.9.3.1 main function [basic.start.main]

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      CWG 1003C++98supported parameter names ofmain were overly restrictedall valid parameter
      names are supported
      CWG 1886C++98themain function could be declared with a language linkageprohibited
      CWG 2479C++20themain function could be declaredconstevalprohibited
      CWG 2811C++98whether themain function is used afterN3214 was unclearit is considered used when named

      [edit]See also

      C documentation formain function
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/main_function&oldid=182698"

      [8]ページ先頭

      ©2009-2025 Movatter.jp