Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      Declarations

      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
       
      Declarations
       

      Declarations are how names are introduced (or re-introduced) into the C++ program. Not all declarations actually declare anything, and each kind of entity is declared differently.Definitions are declarations that are sufficient to use the entity identified by the name.

      A declaration is one of the following:

      • Attribute declaration (attr;)
      (since C++11)
      • Empty declaration (;)
      • A function declaration without adecl-specifier-seq :
      attr (optional)declarator;
      attr -(since C++11) sequence of any number ofattributes
      declarator - a function declarator
      This declaration must declare a constructor, destructor, or user-defined typeconversion function. It can only be used as part of atemplate declaration,explicit specialization, or explicit instantiation.
      • block-declaration (a declaration that can appear inside ablock), which, in turn, can be one of the following:
      (since C++11)
      (since C++20)
      (since C++11)
      • simple declaration

      Contents

      [edit]Simple declaration

      A simple declaration is a statement that introduces, creates, and optionally initializes one or several identifiers, typically variables.

      decl-specifier-seqinit-declarator-list (optional); (1)
      attrdecl-specifier-seqinit-declarator-list; (2)(since C++11)
      decl-specifier-seq - sequence ofspecifiers
      init-declarator-list - comma-separated list ofinit-declarator s (see below)
      attr - sequence of any number ofattributes


      init-declarator-list can only be omitted when declaring a named class or a named enumeration.

      Astructured binding declaration is also a simple declaration.

      (since C++17)


      The syntax ofinit-declarator is defined as follows:

      declaratorinitializer (1)
      declaratorrequires-clause (optional)contract-specs (optional) (2)
      1) A declarator with an initializer.
      2) A declarator without an initializer.
      declarator - adeclarator
      initializer - aninitializer
      requires-clause -(since C++20) arequires clause
      contract-specs -(since C++26) a list offunction contract specifiers


      requires-clause can only appear ifdeclarator declares atemplated function.

      (since C++20)

      contract-specs can only appear ifdeclarator declares a function or function template.

      (since C++26)

      [edit]Specifiers

      Declaration specifiers (decl-specifier-seq) is a sequence of the following whitespace-separated specifiers, in any order:

      • theinline specifier is also allowed on variable declarations.
      (since C++17)
      • thefriend specifier, allowed in class and function declarations.
      • theconstexpr specifier, only allowed in variable definitions, function and function template declarations, and the declaration of static data members of literal type.
      (since C++11)
      • theconsteval specifier, only allowed in function and function template declarations.
      • theconstinit specifier, only allowed in declaration of a variable with static or thread storage duration. At most one of theconstexpr,consteval, andconstinit specifiers is allowed to appear in adecl-specifier-seq.
      (since C++20)
      • storage class specifier (register,(until C++17)static,thread_local,(since C++11)extern,mutable). Only one storage class specifier is allowed, except thatthread_local may appear together withextern orstatic(since C++11).
      • Type specifiers (type-specifier-seq), a sequence of specifiers that names a type. The type of every entity introduced by the declaration is this type, optionally modified by the declarator (see below). This sequence of specifiers is also used bytype-id. Only the following specifiers are part oftype-specifier-seq, in any order:
      (since C++11)
      (since C++26)
      (since C++17)
      • the keywordclass,struct, orunion, followed by the identifier (optionallyqualified), previously defined as the name of a class.
      • the keywordclass,struct, orunion, followed by template name with template arguments (optionallyqualified, optionally usingtemplate disambiguator), previously defined as the name of a class template.
      • the keywordenum followed by the identifier (optionallyqualified), previously declared as the name of an enumeration.
      only one type specifier is allowed in a decl-specifier-seq, with the following exceptions:
      • const can be combined with any type specifier except itself.
      • volatile can be combined with any type specifier except itself.
      • signed orunsigned can be combined withchar,long,short, orint.
      • short orlong can be combined withint.
      • long can be combined withdouble.
      • long can be combined withlong.
      (since C++11)

      Attributes may appear indecl-specifier-seq, in which case they apply to the type determined by the preceding specifiers.

      Repetitions of any specifier in adecl-specifier-seq, such asconststaticconst, orvirtualinlinevirtual are errors, except thatlong is allowed to appear twice(since C++11).

      [edit]Declarators

      Eachinit-declarator in aninit-declarator-listS D1, D2, D3; is processed as if it were a standalone declaration with the same specifiers:S D1; S D2; S D3;.

      Each declarator introduces exactly one object, reference, function, or (for typedef declarations) type alias, whose type is provided bydecl-specifier-seq and optionally modified by operators such as& (reference to) or[] (array of) or() (function returning) in the declarator. These operators can be applied recursively, as shown below.

      Adeclarator is one of the following:

      unqualified-idattr (optional) (1)
      qualified-idattr (optional) (2)
      ...identifierattr (optional) (3)(since C++11)
      *attr (optional)cv (optional)declarator (4)
      nested-name-specifier*attr (optional)cv (optional)declarator (5)
      &attr (optional)declarator (6)
      &&attr (optional)declarator (7)(since C++11)
      noptr-declarator[constant-expression (optional)]attr (optional) (8)
      noptr-declarator(parameter-list)cv (optional)ref  (optional)except (optional)attr (optional) (9)
      (declarator) (10)
      1) Thename that is declared.
      2) A declarator that uses aqualified identifier (qualified-id) defines or redeclares a previously declarednamespace member orclass member.
      3)Parameter pack, only appears inparameter declarations.
      4)Pointer declarator: the declarationS* D; declaresD as a pointer to the type determined bydecl-specifier-seqS.
      5)Pointer to member declaration: the declarationS C::* D; declaresD as a pointer to member ofC of type determined bydecl-specifier-seqS.nested-name-specifier is asequence of names and scope resolution operators::
      6)Lvalue reference declarator: the declarationS& D; declaresD as an lvalue reference to the type determined bydecl-specifier-seqS.
      7)Rvalue reference declarator: the declarationS&& D; declaresD as an rvalue reference to the type determined bydecl-specifier-seqS.
      8)Array declarator.noptr-declarator any valid declarator, but if it begins with *, &, or &&, it has to be surrounded by parentheses.
      9)Function declarator.noptr-declarator any valid declarator, but if it begins with *, &, or &&, it has to be surrounded by parentheses.It may end with the optional trailing return type.(since C++11)
      10) Parenthesized declarator.

      In all cases,attr is an optional sequence ofattributes. When appearing immediately after the identifier, it applies to the object being declared.

      (since C++11)

      cv is a sequence ofconst and volatile qualifiers, where either qualifier may appear at most once in the sequence.

      This section is incomplete
      Reason: explain declaration name hiding rules; how a variable/function declaration hides a class (but not a typedef) with the same name

      [edit]Notes

      When ablock-declaration appearsinside a block, and an identifier introduced by a declaration was previously declared in an outer block, theouter declaration is hidden for the remainder of the block.

      If a declaration introduces a variable with automatic storage duration, it is initialized when its declaration statement is executed. All automatic variables declared in a block are destroyed on exit from the block (regardless how the block is exited: viaexception,goto, or by reaching its end), in order opposite to their order of initialization.

      [edit]Example

      Note: this example demonstrates how some complex declarations are parsed in terms of the language grammar. Other popular mnemonics are:the spiral rule, readinginside-out, anddeclaration mirrors use. There is also an automated parser athttps://cdecl.org.

      Run this code
      #include <type_traits> struct S{int member;// decl-specifier-seq is "int"// declarator is "member"} obj,*pObj(&obj);// decl-specifier-seq is "struct S { int member; }"// declarator "obj" declares an object of type S// declarator "*pObj" declares a pointer to S,//     and initializer "(&obj)" initializes it int i=1,*p= nullptr, f(),(*pf)(double);// decl-specifier-seq is "int"// declarator "i" declares a variable of type int,//     and initializer "= 1" initializes it// declarator "*p" declares a variable of type int*,//     and initializer "= nullptr" initializes it// declarator "f()" declares (but doesn't define)//     a function taking no arguments and returning int// declarator "(*pf)(double)" declares a pointer to function//     taking double and returning int int(*(*var1)(double))[3]= nullptr;// decl-specifier-seq is "int"// declarator is "(*(*var1)(double))[3]"// initializer is "= nullptr" // 1. declarator "(*(*var1)(double))[3]" is an array declarator://    Type declared is: "(*(*var1)(double))" array of 3 elements// 2. declarator "(*(*var1)(double))" is a pointer declarator://    Type declared is: "(*var1)(double)" pointer to array of 3 elements// 3. declarator "(*var1)(double)" is a function declarator://    Type declared is: "(*var1)" function taking "(double)",//    returning pointer to array of 3 elements.// 4. declarator "(*var1)" is a pointer declarator://    Type declared is: "var1" pointer to function taking "(double)",//    returning pointer to array of 3 elements.// 5. declarator "var1" is an identifier.// This declaration declares the object var1 of type "pointer to function// taking double and returning pointer to array of 3 elements of type int"// The initializer "= nullptr" provides the initial value of this pointer. // C++11 alternative syntax:auto(*var2)(double)->int(*)[3]= nullptr;// decl-specifier-seq is "auto"// declarator is "(*var2)(double) -> int (*)[3]"// initializer is "= nullptr" // 1. declarator "(*var2)(double) -> int (*)[3]" is a function declarator://    Type declared is: "(*var2)" function taking "(double)", returning "int (*)[3]"// ... int main(){    static_assert(std::is_same_v<decltype(var1), decltype(var2)>);}

      [edit]Defect reports

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

      DRApplied toBehavior as publishedCorrect behavior
      CWG 482C++98the declarators of redeclarations could not be qualifiedqualified declarators allowed
      CWG 569C++98a single standalone semicolon was not a valid declarationit is an empty declaration,
      which has no effect
      CWG 1830C++98repetition of a function specifier in adecl-specifier-seq was allowedrepetition is forbidden

      [edit]See also

      C documentation forDeclarations
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/declarations&oldid=183368"

      [8]ページ先頭

      ©2009-2025 Movatter.jp