Small details of using functions

Source: Internet
Author: User

function formal Parameters

It is recommended that you use a reference call whenever possible, using a constant reference without modifying the value of the reference parameter. (a value reference is equivalent to a copy of the value of an argument to the parameter, in copying a large class object or a container object is inefficient, even some class type does not support the copy, the function can only access the object of the type by reference to the parameter) the function does not change the parameters of the definition of (normal) reference is a common error, Doing so will mislead the function caller that the function can modify the value of its arguments. In addition, using a reference to a very large reference also greatly restricts the type of arguments that the function can accept. For example, you cannot pass a const object, a literal value, or an object that needs to be converted to a normal reference parameter.

As with all initializations, the top-level const is ignored when the argument is initially taxiing.

Sometimes you may encounter cases where you do not know how many arguments should be passed to the function, and if all arguments are of the same type , you can use the standard library type of initializer_list. Initializer_list is a template type that, like a vector, needs to determine its element type beforehand (using angle brackets <>), it is important to note that the elements in the Initializer_list object are always constant values . Since initializer_list contains the begin and end members, all of them can be processed using the scope for loop. You can use a mutable type template if the argument types are not the same .

return value of the function

do not return a reference or pointer to a local object , the life cycle of a local non-static object is preceded by the end of the function body, and the storage space it occupies is freed when the function completes, so this means that the reference or pointer to the local variable will point to the area that is no longer valid.

The call operator (parentheses ()) also has a precedence and binding law. The call operator has the same precedence and point operator as the arrow operator and satisfies the left binding law, so if the function returns a pointer, the object of the reference or class can directly access the members of the result object.

Auto Sz = shorterstring (S1,S2). Size ();//The reuse of the call operator and the dot operator to obtain the length of a shorter string object in a shorter form


Calling a function that returns a reference gets an lvalue , and the other return type gets the right value .

C++11 New standard specifies that you can return a list of values enclosed in curly braces , where the list can also initialize a temporary amount that represents the return value of a function, and if the list is empty, the value is initialized, otherwise the returned value is determined by the type of the function.

The function cannot return an array, but can return an array pointer, which is cumbersome to return the function definition of the array pointer. To define a function that returns an array pointer, the array dimension must immediately follow the function parameter list . The function that returns an array pointer is as follows:

Type (*function (parameter_list)) [Dimension]//type---element type//dimension---array size
int (*func (int i)) [10];


The understanding of an instance is from the Inside out, (int i) the first parameter of the Func function is a value of type int, (*func (int i)) indicates that the result of a function call can perform a dereference operation, that is, the result returned by the function is a pointer;

Look at the parentheses to the right, indicating that the pointer is to an array of 10 elements, and finally the base data type int, which indicates that the array element is of type int.

There are two ways to simplify the definition of a function that returns an array pointer:

1. Using Type aliases

Using ARRT = INT[10];//ARRT is a type alias, which represents the type of a 10-element shaped array arrt* func (int i);      The Func function returns a pointer to an array of 10 integers (the type alias is considered to be a encapsulated whole and cannot be reverted to the declaration to understand)


2.c++11 the new standard can be defined using the tail return type , followed by a trailing return type after the parameter list and preceded by a symbol.

Auto func (int i)->int (*) [10];


function overloading

If several functions within a scope have the same name, but the formal parameter list (the return type is not the same and the egg) is not the same (cannot distinguish the top-level const, but can distinguish the underlying const), we call the overloaded (overload) function.

In a function overload, there is always the need to change the const property of the object, when a good base friend const_cast out to help. Const_cast can and can only change the underlying const property of an object.

Const string &shortstring (const string &s1,const string &s2) {       return s1.size () <= s2.size ()? S1:s2;}


The return type and parameter type of the function in the example above are a const string reference, and the function can use two very different arguments, but the return type is also a reference to the const string. You can use the following overloaded versions:

String &shorterstring (String &s1,string &s2)//function overloading can distinguish the underlying const, the constant reference is the underlying const{       auto &r = Shorterstring (Const_cast<const string &>s1,const_cast<const string &>s2);//The function returns a reference to the const type     return const_cast<string &> (r);//Remove Const Property}


It is recommended that the function declaration be placed outside the local scope , and if the function is declared in the memory scope, it hides the entity with the same name declared in the outer scope.

In the C + + language, a name lookup occurs before a type lookup .

Default actual parameters

In multiple invocations of a function, an argument is given the same value, and we call this recurring value the default argument of the function. Calling a function that contains a default argument can include the argument or omit the argument. It is important to note that once a parameter has been given a default value, all parameters after it must have a default value. (When designing functions that contain default arguments, the order of formal parameters must be set appropriately, and the parameters that often use the default values appear later).

You should typically specify a default argument in a function declaration and place the declaration in the appropriate header file.

a local variable cannot be the default argument . Even if we declare a local variable inside the function to hide the external variable, the local variable cannot update the value of the corresponding parameter as the default argument.

inline functions and CONSTEXPR functions

inline function (inline) refers to the expansion of "inline" at each call point (presumably in the form of equivalent equivalents) to reduce the overhead required to invoke the function. Calling a function requires a series of work: Save the Register before the call and restore it on return; you may need to copy the arguments; The program moves to a new location to continue execution.

In general, the inline mechanism is used only to optimize some functions that are small, straightforward, and frequently called. Adding inline at the top of the function indicates that an inline request is made to the compiler, and the compiler can choose to ignore the request.

The constexpr function refers to a function that can be used for constant expressions. The return value type of the CONSTEXPR function and all parameter types must be literal types, and the function weight must have only one return statement. The CONSTEXPR function is implicitly specified as an inline function.

Assert preprocessing macros and ndebug pre-processing variables---Debugging program's auxiliary means

ASSERT (expr); The first evaluation of expr, if the 0,assert output information and terminate the operation of the program, if the 1,assert do nothing. The Assert macro is often used to check for "cannot occur" conditions .

Defining Ndebug avoids the runtime overhead required to check for various conditions, and run-time checks are not performed at this time. (for example, when Ndebug is defined, the assert will not do anything)

The C + + compiler defines a __func__for each function, which is a static array of const Char that holds the name of the function.

The C + + preprocessor defines 4 names that are useful for debugging a program:

__file__ string literals for storing file names

__line__ the shape literal value of the current line number

__time__ string literals that store file compilation time

__date__ string literals that store file compilation dates

function matching

The compiler first determines the set of candidate functions and then selects a viable match (if there is no viable function, the compiler will report an error with no matching function), and finally the best match, if any. The match succeeds if there is only one function in all the possible functions that satisfies the following conditions:

1. The match for each argument of the function is no less than the matching required by other viable functions.

2. A match with at least one argument is better than the match provided by other viable functions.

If none of the functions stand out, the compiler reports the information that ambiguity calls.

Conversions and boosts that require built-in types may cause a two semantic invocation error when a function is matched (all arithmetic type conversions are the same level, and the conversion from int to unsigned int is no higher than the conversion level of int to double).

void Mainip (long), void Mainip (float), mainip (3.14);//Error: Ambiguity call


The double type can be converted either to float or to long because there are two possible transformations, so the invocation is ambiguous.

As previously mentioned, function overloading can differentiate between the underlying const (reference and pointer const), and when a call occurs, the compiler determines which function to select by whether the argument is a constant.

function pointers

To declare a pointer that you can point to the function, simply replace it with a pointer.

BOOL (*PF) (const string &,const string &);


Like an array, when we use the function name as a value, the function is automatically converted to a pointer.

There is no type conversion rule between pointers pointing to different function types.

If you assign a nullptr to a function pointer or an integer value of 0, it means that the pointer does not point to any function.

When we use the pointer type to decide which function to choose, the pointer to the overloaded function must match an exact one in the overloaded function (the type of the pointer and the return type of the function to match, and the parameter list to match).

A function can return a pointer to a function that is similar to a function that returns a pointer to an array, using the trailing return type to represent the return type.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Small details of using functions

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.