Condividi tramite


Function Declaration Syntax 

Functions may be global or members of a class or struct. They are declared using the following sequence:

[friend] [storage-class-specifier] [function-specifier]
[[cv-qualifer] type-specifier] declarator [cv-qualifer] 
[exception-spec]
[friend] [storage-class-specifier] [function-specifier]
[[cv-qualifer] type-specifier] [*|&] [ms-modifer] identifier 
( argument-list ) [cv-qualifer] [exception-spec]
  1. The declaration specifier. See Specifiers.

    • Within a class, an optional friend specifier.

    • An optional storage class specifier. For global functions, allowable storage class specifiers are static and extern. For class member functions, extern is not allowed.

    • An optional function specifier. For global functions, the only allowable function specifier is inline. For class member functions, virtual and inline are allowed and, for constructors, explicit.

    • A type specifier indicating the return type (subject to modification to a pointer or reference type by the use of * or &).

  2. The declarator.

    • Optional pointer or reference operator(s) modifying the return type

    • An optional Microsoft specific modifier specifying the calling convention. See Microsoft Specific Modifiers.

    • The name of the function. If the function is a member of a class or struct, the name may be qualified using the scope resolution operator.

    • The argument declaration list enclosed in parentheses ().

    • An optional const or volatile qualifier. In this context, const may only be used for class members, and is used to indicate that the function will not modify data members of the class.

If the return type is a function pointer, the syntax of the declarator may be more complex, as explained below.

  1. An optional exception specification indicating what exception(s) the function throws. See Exception Specifications.

The type of the identifier so declared may be constructed as follows: const or volatile (if specified) function, taking the specified argument list, returning the type indicated by the declaration specifier.

The following example shows two simple function declarations:

char *strchr( char *dest, char *src );
static int atoi( const char *ascnum ) const;

Declaring Functions Returning Pointers to Functions

It is recommended that typedef be used to declare an alias for the function pointer type if declaring a function that returns a function pointer type. For example

typedef int (*fp)(int);
fp myFunction(char* s); // function returning function pointer

If this is not done, the proper syntax for the function declaration may be deduced from the declarator syntax for the function pointer by replacing the identifier (fp in the above example) with the functions name and argument list, as follows:

int (*myFunction(char* s))(int);

The preceding declaration is equivalent to the declaration using typedef above.

See Also

Reference

Function Declarations