Basic knowledge of function use in C + + learning tutorials _c language

Source: Internet
Author: User
Tags function definition

A function is a block of code that performs some action. A function optionally defines an input parameter that enables callers to pass arguments to a function. The function can optionally return the value as output. Functions can be used to encapsulate common operations in a single reusable block (ideally, using a name that clearly describes the function's behavior). The following function accepts two integers from the caller and returns their sum; A and B are parameters of type int.

int sum (int a, int b)
{return
  a + b;
}

Functions can be called from any number of locations in the program. The value passed to the function is an argument whose type must be compatible with the formal parameter type in the function definition.

int main ()
{
  int i = SUM (a);
  int j = SUM (i,);
  cout << "The value of J is" << J << Endl; 108
}

There is no actual limit to the length of a function, but a good design should target a function that performs a single well-defined task. Complex algorithms should be decomposed as far as possible into simpler functions that are easy to understand.
functions defined in the scope of a class are called member functions. In C + + (unlike other languages), a function can also be defined in a namespace scope, including an implicit global namespace. These functions are called free or non-member functions, and they are widely used in standard libraries.
various parts of a function declaration
the minimum function declaration contains a return type, a function name, and a list of arguments (which may be empty), and an optional keyword that provides additional instructions to the compiler. The function definition contains the declaration and the Body of the function (this is all the code between the braces). A function declaration that is followed by a semicolon can appear in multiple locations in the program. It must appear before any calls to the function in each translation unit. Depending on a single definition rule (ODR), the function definition must appear only once in the program.
The necessary parts of a function declaration are:
Returns a type that specifies the type of the value that the function will return, or void if no value is returned. In c++11, Auto is a valid return type that instructs the compiler to infer the type from the return statement. In C++14, Decltype (auto) is also allowed. For more information, see "type derivation in the return type" below.
The function name must begin with a letter or underscore and cannot contain spaces. In general, a leading underline in a standard library function name indicates a private member function, or not a member function that is used by your code.
A list of arguments (a set of 0 or more parameters delimited by braces, comma-separated), specifying a type and an optional local variable name that can be used to access the value in the function body.
The optional parts of the function declaration are:
Constexpr, indicates that the return value of the function is a constant value that can be evaluated at compile time.

       CONSTEXPR float exp (float x, int n)
{return
  n = 0? 1:
    n% 2 = 0? exp (x * x, N/2): exp (x * * x,
    (N- 1)/2) * x;
};

Its linkage specification (extern or static).

Declare printf with C linkage.
extern "C" int printf (const char *fmt, ...);

Inline, instructs the compiler to replace each invocation of the function with the function code itself. Inline can help improve performance when a function is executed quickly and repeatedly called in performance-critical code snippets.

Inline double account::getbalance ()
{return
  balance;
}

NOEXCEPT Specifies whether the function can throw an exception. In the following example, the function does not throw an exception when the Is_pod expression evaluates to True.

#include <type_traits>

template <typename t>
T copy_object (t& obj) noexcept (std::is_pod< t>) {...}

member function only) CV qualifier, specifying whether the function is const or volatile.
(member functions only) virtual, override, or final. virtual specifies that a function can be overridden in a derived class. Override represents a function in a derived class that overrides a virtual function. The final representation function cannot be overridden in any further derived classes.

(only member functions only) the static representation function applied to a member function is not associated with any object instance of the class.
(Non-static member function only) the REF qualifier, which specifies to the compiler that an implicit object parameter (*this) is the function overload to select when the right reference is referenced with the left value reference.
The following illustration shows the various parts of a function definition. The gray area is the function body.

function Definition Section
function definition
a variable declared in a function body is called a local variable. They are out of range when the function exits; therefore, the function should never return a reference to a local variable!
function templates
a function template is similar to a class template, and it generates specific functionality based on template parameters. In many cases, templates can infer type parameters, so you do not need to specify them explicitly.

Template<typename Lhs, TypeName rhs>
auto Add2 (const lhs& LHS, const rhs& RHS)
{return
  LHS + RH s;
}

Auto A = ADD2 (3.13, 2.895); A is a double
auto B = Add2 (string{"Hello"}, string{' World '});//b is a std::string
for more information see function templates

function parameters and arguments
a function has 0 or more types of comma-delimited list of parameters, each of which has a name that can be used to access it in the body of a function. Function templates can specify other types or value parameters. The caller passes the argument whose type is a specific value compatible with the parameter list.
By default, a parameter is passed to a function by value, which means that the function receives a copy of the object being passed. For large objects, creating replicas can be costly and not always necessary. To allow arguments to be passed by reference (especially a left-valued reference), add a reference qualifier to the parameter:

void dosomething (std::string& input) {...}

When a function modifies an argument passed by reference, it modifies the original object, not the local copy. To prevent a function from modifying such arguments, limit the parameters to

Const&:
void dosomething (const std::string& input) {...}

C + + 11: To explicitly handle an argument that is passed by a right value reference or by a reference to a left value, use a double number with the parameter to indicate a generic reference:

void dosomething (const std::string&& input) {...}

As long as the key void is the first and only member of the argument declaration list, a function declared with a single keyword void in the parameter declaration list has no arguments. The arguments for void types elsewhere in the list produce an error. For example:

OK Same as GetTickCount ()
long GetTickCount (void); 

Note that although specifying void parameters is illegal (except as described here), types that derive from type void, such as the pointer to void and an array of void, can appear anywhere in the parameter declaration list.
Default Parameters
the last or several parameters in a function signature may be assigned a default argument, which means that the caller may omit the argument when calling the function (unless you want to specify a different value).

int dosomething (int num, 
  string str, 
  allocator& alloc = defaultallocator)
{...}

OK both parameters are at end
int dosomethingelse (int num, 
  string str = string{"Working"}, 
  allocator& Alloc = defaultallocator)
{...}

C2548: ' domore ': missing default parameter for parameter 2
int domore (int num = 5,//not a trailing parameter!
   string str,
  allocator& = defaultallocator)
{...}

function return type
the function may not return another function or a built-in array, but it can return a pointer to those types, or a lambda that generates a function object. In addition to these cases, a function can return any type of value that is in scope, or it can return any value (in which case the return type is void).
End return type
The normal return type is located to the left of the function signature. The end return type is at the far right of the signature, preceded by the-> operator. The end return type is especially useful in function templates when the type of the return value depends on the template parameter.

Template<typename Lhs, TypeName rhs>
auto Add (const lhs& LHS, const rhs& RHS)-> decltype (Lhs + Rhs)
{return
  LHS + RHS; 
}

When auto and the end return type are used in combination, any content that it generates for the Decltype expression is used only as a placeholder and does not perform type derivation itself.
Type derivation in the return type (C++14)
In c++14, you can use auto to instruct the compiler to infer a return type from a function body without having to provide the end return type. Note that auto is always deduced to return by value. Use auto&& to instruct the compiler to infer a reference.
In this example, auto is deduced as a very lhs copy of the sum of the RHS and the sum of the values.

Template<typename Lhs, TypeName rhs>
auto Add2 (const lhs& LHS, const rhs& RHS)
{return
  LHS + RH S Returns a Non-const object by value
}

Note that auto does not retain the constant nature of the type it derives. For a return value that requires a constant or referential forwarding function that retains its arguments, you can use the Decltype (auto) keyword, which uses the Decltype type to infer rules and retain all type information. Decltype (auto) can be used as the normal return value on the left, or at the end of the return value.
The following example, based on the code from N3493, demonstrates that Decltype (auto) is used to perform the perfect forwarding of function arguments using a return type that is unknown before the template is instantiated.

 Template<typename F, typename Tuple = tuple<t...>, int ... I> decltype (Auto) apply_ (f&& F, tuple&& args, index_sequence<i...>) {return std::forward<f
> (f) (Std::get<i> (std::forward<tuple> (args)); } template<typename F, typename Tuple = Tuple<t...>, typename Indices = Make_index_sequence<tuple_size<t Uple>::value >> decltype (Auto) apply (f&& F, tuple&& args) {return apply_ (STD::FORWARD&L T
F> (f), std::forward<tuple> (args), Indices ()); }
}

function local variable
A variable declared inside a function body is called a local variable. Non-static local variables are visible only in the body of the function, and if they are declared on the stack, they will go out of scope when the function exits. When you construct a local variable and return it by value, the compiler can usually perform a return value optimization to avoid unnecessary replication operations. If a local variable is returned by reference, the compiler emits a warning because any attempt by the caller to use the reference occurs after the local variable has been destroyed.
The local static object will be destroyed during the atexit specified termination. If a static object is not constructed because the program's control flow skips its declaration, the object is not attempted to be destroyed.
Static Local Variables
in C + +, local variables can be declared static. The variable is visible only in the body of the function, but for all instances of the function, a single copy of the variable exists.
function pointers
C + + supports function pointers in the same way as the C language. But a more type-safe alternative is usually to use a function object.
It is recommended that you use TypeDef to declare aliases for function pointer types (if you declare functions that return function pointer types). For example

typedef int (*FP) (int);
FP MyFunction (char* s); function Returning function pointer

If this is not done, the correct syntax for the function declaration can be deduced from the declaration syntax of the function pointer by replacing the identifier with the function name and the argument list, as shown in the following example:

Int (*myfunction (char* s)) (int);

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.