Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/language/functions"

From cppreference.com
< cpp‎ | language
(Undo revision 134351 by Asdfasdf (talk))
m (fmt)
 
(19 intermediate revisions by 10 users not shown)
Line 9: Line 9:
 
// the return type is bool
 
// the return type is bool
 
bool isodd(int n)
 
bool isodd(int n)
{                     // the body of the function begins
+
{                 // the body of the function begins
 
     return n % 2;
 
     return n % 2;
}                     // the body of the function ends
+
}                 // the body of the function ends
 
}}
 
}}
  
When a function is invoked, e.g. in a {{rlp|operator_other#Built-in_function_call_operator|function-call expression}}, the parameters are initialized from the arguments (either provided at the place of call or {{rlp|default_arguments|defaulted}}) and the statements in the function body are executed. If the {{rlp|function#Parameter list|parameter list}} ends with {{c|...}}, extra arguments can be supplied to the function, such a function is called {{rlp|variadic arguments|variadic function}}.
+
When a function is invoked, e.g. in a {{rlp|operator other#Built-in function call operator|function-call expression}}, the parameters are initialized from the arguments (either provided at the place of call or {{rlp|default arguments|defaulted}}) and the statements in the function body are executed. If the {{rlp|function#Parameter list|parameter list}} ends with {{c|...}}, extra arguments can be supplied to the function, such a function is called {{rlp|variadic arguments|variadic function}}.
  
 
{{source|
 
{{source|
 
int main()
 
int main()
 
{
 
{
     for(int arg : {-3, -2, -1, 0, 1, 2, 3})
+
     for (int arg : {-3, -2, -1, 0, 1, 2, 3})
 
         std::cout << isodd(arg) << ' '; // isodd called 7 times, each
 
         std::cout << isodd(arg) << ' '; // isodd called 7 times, each
 
                                         // time n is copy-initialized from arg
 
                                         // time n is copy-initialized from arg
Line 33: Line 33:
 
}}
 
}}
  
A {{rlp|function|function declaration}} may appear in any scope, but a {{rlp|function|function definition}} may only appear in namespace scope or, for {{rlp|member_functions|member}} and {{rlp|friend}} functions, in class scope. A function that is declared in a class body without a friend specifier is a class member function. Such functions have many additional properties, see {{rlp|member_functions|member functions}} for details.
+
A {{rlp|function|function declaration}} may appear in any scope, but a {{rlp|function|function definition}} may only appear in namespace scope or, for {{rlp|member functions|member}} and {{rlp|friend}} functions, in class scope. A function that is declared in a class body without a friend specifier is a class member function. Such functions have many additional properties, see {{rlp|member functions}} for details.
  
Functions are not objects: there are no arrays of functions and functions cannot be passed by value or returned from other functions. Pointers and references to {{rev inl|until=c++20|functions}}{{rev inl|since=c++20|non standard library functions and {{rlp|extending std#Addressable functions|a few standard library functions}}}} are allowed, and may be used where these functions themselves cannot. Therefore we say these functions are "addressable".
+
Functions are not objects: there are no arrays of functions and functions cannot be passed by value or returned from other functions. Pointers and references to functions (except for {{rlp|main function|the main function}}{{rev inl|since=c++20| and {{rlp|extending std#Addressing restriction|most standard library functions}}}}) are allowed, and may be used where these functions themselves cannot. Therefore we say these functions are "addressable".
  
Each function has a type, which consists of the function's return type, the types of all parameters (after array-to-pointer and function-to-pointer transformations, see {{rlp|function#Parameter list|parameter list}}) {{rev inl|since=c++17|, whether the function is {{rlpt|noexcept spec|noexcept}} or not}}, and, for non-static member functions, cv-qualification{{rev inl|since=c++11| and ref-qualification}}. Function types also have {{rlp|language_linkage|language linkage}}. There are no cv-qualified function types (not to be confused with the types of {{rlp|member_functions|cv-qualified functions}} such as {{c|int f() const;}} or functions returning {{rlp|cv|cv-qualified types}}, such as {{c|std::string const f();}}). Any cv-qualifier is ignored if it is added to an alias for a function type.<!-- CWG295 -->
+
Each function has a type, which consists of the function's return type, the types of all parameters (after array-to-pointer and function-to-pointer transformations, see {{rlp|function#Parameter list|parameter list}}) {{rev inl|since=c++17|, whether the function is {{rlpt|noexcept spec|noexcept}} or not}}, and, for non-static member functions, cv-qualification{{rev inl|since=c++11| and ref-qualification}}. Function types also have {{rlp|language linkage}}. There are no cv-qualified function types (not to be confused with the types of {{rlp|member functions|cv-qualified functions}} such as {{c|int f() const;}} or functions returning {{rlp|cv|cv-qualified types}}, such as {{c|std::string const f();}}). Any cv-qualifier is ignored if it is added to an alias for a function type.<!--CWG295-->
 +
 
 +
Multiple functions in the same scope may have the same name, as long as their parameter lists and, for non-static member functions, cv{{rev inl|since=c++11|/ref}}-qualifications are different. This is known as {{rlp|overload resolution|function overloading}}. Function declarations that differ only in the return type {{rev inl|since=c++17|and the noexcept specification}} cannot be overloaded. The {{rlp|overloaded address|address of an overloaded function}} is determined differently.
  
 
{{rrev|since=c++11|
 
{{rrev|since=c++11|
Unnamed functions can be generated by {{rlp|lambda|lambda-expressions}}.
+
C++ implements {{enwiki|anonymous function}}s using {{rlp|lambda|lambda-expressions}}.
 
}}
 
}}
 
Multiple functions in the same scope may have the same name, as long as their parameter lists and, for non-static member functions, cv{{rev inl|since=c++11|/ref}}-qualifications are different. This is known as {{rlp|overload_resolution|function overloading}}. Function declarations that differ only in the return type {{rev inl|since=c++17|and the noexcept specification}} cannot be overloaded. The {{rlp|overloaded address|address of an overloaded function}} is determined differently.
 
  
 
===Function objects===
 
===Function objects===
 
Besides function lvalues, the function call expression supports pointers to functions, and any value of class type that overloads the function-call operator or is convertible to function pointer{{rev inl|since=c++11| (including {{rlp|lambda|lambda-expressions}})}}. Together, these types are known as {{named req|FunctionObject}}s, and they are used ubiquitously through the C++ standard library, see for example, usages of {{named req|BinaryPredicate}} and {{named req|Compare}}.
 
Besides function lvalues, the function call expression supports pointers to functions, and any value of class type that overloads the function-call operator or is convertible to function pointer{{rev inl|since=c++11| (including {{rlp|lambda|lambda-expressions}})}}. Together, these types are known as {{named req|FunctionObject}}s, and they are used ubiquitously through the C++ standard library, see for example, usages of {{named req|BinaryPredicate}} and {{named req|Compare}}.
  
The standard library also provides a number of pre-defined [[cpp/utility/functional|function object templates]] as well as the methods to compose new ones (including {{lc|std::less}}{{rev inl|since=c++11|, {{lc|std::mem_fn}}, {{lc|std::bind}}, and {{lc|std::function}}}}).
+
The standard library also provides a number of predefined [[cpp/utility/functional|function object templates]] as well as the methods to compose new ones (including {{lc|std::less}}{{rev inl|since=c++11|, {{lc|std::mem_fn}}, {{lc|std::bind}}, {{lc|std::function}}}}{{rev inl|since=c++17|, {{lc|std::not_fn}}}}{{rev inl|since=c++20|, {{lc|std::bind_front}}}}{{rev inl|since=c++23|, {{lc|std::bind_back}}, {{lc|std::move_only_function}}}}{{rev inl|since=c++26|, {{lc|std::copyable_function}}, and {{lc|std::function_ref}}}}).
  
 
{{langlinks|es|ja|ru|zh}}
 
{{langlinks|es|ja|ru|zh}}

Latest revision as of 05:33, 2 October 2023

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
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
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

Functions are C++ entities that associate a sequence of statements (a function body) with a name and a list of zero or more function parameters.

// function name: "isodd"
// parameter list has one parameter, with name "n" and type int
// the return type is bool
bool isodd(int n)
{                 // the body of the function begins
    return n % 2;
}                 // the body of the function ends

When a function is invoked, e.g. in a function-call expression, the parameters are initialized from the arguments (either provided at the place of call or defaulted) and the statements in the function body are executed. If the parameter list ends with ..., extra arguments can be supplied to the function, such a function is called variadic function.

int main()
{
    for (int arg : {-3, -2, -1, 0, 1, 2, 3})
        std::cout << isodd(arg) << ' '; // isodd called 7 times, each
                                        // time n is copy-initialized from arg
}

Unqualified function names in function-call expressions are looked up with an extra set of rules called "argument-dependent lookup" (ADL).

A function can terminate by returning or by throwing an exception.

A function may be a coroutine, in which case it can suspend execution to be resumed later.

(since C++20)

A function declaration may appear in any scope, but a function definition may only appear in namespace scope or, for member and friend functions, in class scope. A function that is declared in a class body without a friend specifier is a class member function. Such functions have many additional properties, see member functions for details.

Functions are not objects: there are no arrays of functions and functions cannot be passed by value or returned from other functions. Pointers and references to functions (except for the main function and most standard library functions(since C++20)) are allowed, and may be used where these functions themselves cannot. Therefore we say these functions are "addressable".

Each function has a type, which consists of the function's return type, the types of all parameters (after array-to-pointer and function-to-pointer transformations, see parameter list) , whether the function is noexcept or not(since C++17), and, for non-static member functions, cv-qualification and ref-qualification(since C++11). Function types also have language linkage. There are no cv-qualified function types (not to be confused with the types of cv-qualified functions such as int f() const; or functions returning cv-qualified types, such as std::string const f();). Any cv-qualifier is ignored if it is added to an alias for a function type.

Multiple functions in the same scope may have the same name, as long as their parameter lists and, for non-static member functions, cv/ref(since C++11)-qualifications are different. This is known as function overloading. Function declarations that differ only in the return type and the noexcept specification(since C++17) cannot be overloaded. The address of an overloaded function is determined differently.

C++ implements anonymous functions using lambda-expressions.

(since C++11)

[edit] Function objects

Besides function lvalues, the function call expression supports pointers to functions, and any value of class type that overloads the function-call operator or is convertible to function pointer (including lambda-expressions)(since C++11). Together, these types are known as FunctionObjects, and they are used ubiquitously through the C++ standard library, see for example, usages of BinaryPredicate and Compare.

The standard library also provides a number of predefined function object templates as well as the methods to compose new ones (including std::less, std::mem_fn, std::bind, std::function(since C++11), std::not_fn(since C++17), std::bind_front(since C++20), std::bind_back, std::move_only_function(since C++23), std::copyable_function, and std::function_ref(since C++26)).