C + + system learning Six: Functions

Source: Internet
Author: User
Tags assert closing tag function definition int size
1. Function basics

Typical function definitions include: return type, function name, a list of 0 or more formal parameters, and a function body.

2. Parameter passing

The mechanism of parameter initialization is the same as the initialization of variables.

There are two ways: reference passing and value passing

2.1 parameter of the pass value

When a formal parameter is a non-reference type, the parameter initialization is the same as the initialization of the variable, and the value of the argument is copied to the parameter.

Pointer parameters

When the pointer copy operation is performed, the value of the pointer is copied, and after the copy, two pointers are different pointers. However, you can modify the object it refers to by using the pointer.

2.2 Pass reference parameter use reference to avoid copying

Copying large class-type objects or container objects is inefficient, and even some class types do not support copy operations at all. When a type does not support copy operations, the function can only access objects of that type through reference parameters.

Using reference parameters to return additional information 2.3 const parameters and arguments

The top-level const is ignored when the const parameter is initialized with an argument. Therefore, when a formal parameter has a top-level const, it is possible to pass it to a constant object or to a very mass object.

void fun1 (const int i) {...} void fun2 (int i) {...}

The above two functions can not be considered overloaded, two functions are the same, the program will error, FUN2 repeatedly defined fun1.

Pointer or reference shape participates in const

An underlying const object can be initialized with a very low volume, but not in the reverse. At the same time a common reference must be initialized with an object of the same type.

Use constants to refer to 2.4 array parameters as much as possible

The array has two important features:

    • Copy not allowed
    • Converts to pointers when using arrays

Although you cannot pass an array as a value, you can write the formal parameter as an array-like form

void print (const int*), void print (const int[]), void print (const INT[10]), and declarations of the above three types are equivalent

Note: The array parameter should be a pointer to the const when the function does not need to perform a write operation on a set of elements. It is only when the function is really changing the value of the element that the formal parameter definition is exponentially to a very high number of pointers.

When an array is a function parameter, you should provide some extra information to determine the exact size of the array, and there are three common techniques for managing array parameters:

Specifying array lengths with tags

Requires that the array itself contain a closing tag. For example, a C-style string ends with a null character.

Using the standard library specification

Passes a pointer to the first and the end elements of the array.

void print (const int *beg,const int *end) {while     (beg!=end)    {         cout<<*beg++<<endl;       }  }    
int arr[2]={0,1};
Print (Begin (ARR), End (arr));
Explicitly passing a formal parameter that represents the size of an array

Specifically defines a formal parameter that represents the size of the array.

void print (const int ia[], size_t size), int j[]={0,1};p rint (J, End (J)-begin (j));
Array reference formal parameters

A formal parameter can be a reference to an array, at which point the reference parameter is bound to the corresponding argument, which is bound to the array.

void print (int (&arr) [ten]) {for    (auto Elem:arr)    {           cout<<elem<<endl;    }} A parameter is a reference to an array, and a dimension is a part of a type

Note:arr brackets at both ends are essential

f (int &arr[10]);    Error, declaring arr as a referenced array f (int (&arr) [ten]);    Right, arr is a reference to an integer array with 10 integers
Passing multidimensional arrays

The size of the second dimension of the array is part of the array type and cannot be omitted. Passing a multidimensional array is a pointer to an array, actually a pointer to the first element. (a multidimensional array is an array of arrays, the first element of an array is an array, so it is a pointer to an array).

void print (int (*matrix) [10],int size);  Matrix is a pointer to an array with 10 integers

You can also use:

void print (int matrix[][10],int size); The matrix has the same meaning as above
2.5 Functions with deformable parameters

C + + offers two ways to:

With the same argument type, you can pass a standard library type named Initializer_list initializer_list parameter

Lnitializer_list and vectors are template types, but the elements in the Initializer_list object are always constant values and cannot be changed.

void error_msg (initializer_list<string> ls) {for (Auto Beg = Ls.begin (); Beg! = Ls.end (); ++beg) {cout << *beg & lt;< "   ";} cout << Endl;}

Error_msg ({"Hello"});
Error_msg ({"hello!", "world!!"}); Note that the value of the pass is placed in curly braces.

Ellipsis parameter

The ellipsis parameters are set to facilitate access by C + + programs to some special C code. Typically, an ellipsis parameter is not applied to other purposes. An ellipsis parameter can only appear at the last position in the formal parameter list.

No return value function using Variadic template 3, return type, and return statement 3.1 with different argument types

return type is a function of type void

3.2 How the return value function value is returned

Returns a value in exactly the same way that a variable or parameter is initialized: The returned value is used to initialize a temporary amount of the call point, which is the result of a function call.

Do not return a reference to a local object or a pointer to a function that returns a class type and a call operator
Auto Sz=getstring (). Size ();    GetString returns a String object to call the size function again
Reference returns the left value

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

List initialization return value

The function can return a list of values enclosed in curly braces.

vector<string>  process () {    return {"Ni", "Hao"};}
Recursive

If a function calls itself, whether the call is direct or indirect, the function is called a recursive function.

int factorial (int val) {    if (val>1)        return factorial (val-1) *val;    return 1;} Ask 1x2x3x4 ...
3.3 Returning an array pointer

The function cannot return an array because the array cannot be copied. However, a function can return a pointer or reference to an array.

The most straightforward approach is to use type aliases

typedef int arrt[10];using ARRT=INT[10];
Declaring a function that returns an array pointer
int arr[10];    Arr is an array of 10 integers int *p1[10];    P1 is an array int (*P2) that contains 10 integer pointers [10]=&arr;    P2 is a pointer to an array with 10 integers

If you want to define a function that returns an array pointer, the dimension of the array must follow the function name, and the parameter list of the function should precede the dimension of the array.

int (*func (int a,int b)) [10];

This function returns a pointer to an array of 10 integers.

Using the tail return type

The definition of any function can be returned with a tail, but this form is most effective for functions that return a complex type, such as a pointer to an array or a reference to a return type.

The trailing return type follows the formal parameter list and begins with a symbol. To indicate that the actual return type of the function is followed by the parameter list, we place an auto in the place where the return type should have occurred.

Auto func (int i)->int (*) [10];
Using Decltype4, function overloading

If several functions within the same scope have the same name but different parameter lists, they are called function overloads. Note that the parameter list must be different, just the return type is different and cannot be called overloading.

Overloads and Const parameters

The top-level const does not affect the object passed into the function. A formal parameter with a top-level const cannot be distinguished from another parameter that has no top-level const.

int F1 (int i); int F1 (const int i);    Does not constitute an overload, repeated declaration of F1int F2 (int *i); int f2 (int *const i);    Does not constitute an overload, repeated declaration of F2

But the underlying const is different and can form overloads

int F1 (int &i); int F1 (const int &i);    Overloads, new functions int f2 (int *i), int f2 (const int *i);    Overloads, new functions

Note: It is best to overload only those operations that are really very similar.

Const_cast and overloading

Const_cast is most useful in scenarios where overloaded functions are available.

Const string &shorterstring (const string &S1, const string &s2) {return s1.size () <= s2.size ()? S1:s2;} String &shorterstring (String &s1, String &s2) {Auto &r = shorterstring (Const_cast<const string& > (S1), Const_cast<const string&> (S2)); return const_cast<string&> (R);}
4.1 Overloads and Scopes

If you declare a name in the inner scope, it hides the entity with the same name declared in the outer scope.

void Func () {    }int main () {        int func=0;    Func ();    Error, when Func is a variable of type int, not a function, hides the outer function definition    return 0;}
5. Special-Purpose language features

Default arguments, inline functions, and constexpr functions.

5.1 Default Arguments

Once a parameter is given a default value, all parameters following it must have a default value.

String screen  (int i=10, int a=1, stirng s= "");
Calling functions with default arguments

Omitting the argument when calling the function is possible.

Default argument declaration

A formal parameter can be assigned only one default argument at a given scope.

Default argument initial value

A local variable cannot be the default argument. In addition, the expression can be used as the default argument as long as the type of the expression can convert the type required by the forming parameter.

5.2 Inline functions and CONSTEXPR functions

Calling a function is generally slower than finding the value of an equivalent expression.

Inline functions to avoid the overhead of function calls

Precede the return type of the function with the keyword inline.

In general, the inline mechanism is used to optimize functions that are small, process-direct, and frequently called.

constexpr function

The constexpr function refers to a function that can be used for constant expressions.

Define the CONSTEXPR function to follow: The return type of the function and the type of all formal parameters are literal types, and there must be only one return statement in the body of the function.

constexpr int NEW_SZ () {        return 42;} constexpr int FOO=NEW_SZ ();    Foo is a constant expression

To be able to expand at any time during the compilation process, the CONSTEXPR function is implicitly specified as an inline function.

The NOTE:CONSTEXPR function does not necessarily return a constant expression.

Put inline functions and constexpr functions inside the header file

Unlike other functions, inline functions and constexpr functions can be defined more than once in a program. However, for a given inline function or constexpr function, its multiple definitions must be exactly the same. Therefore, inline functions and constexpr functions are usually defined in the header file.

5.3 Debugging Help

Two preprocessing functions: Assert and Ndebug

ASSERT preprocessing macros

The Assert macro is often used to check for "cannot occur" conditions.

ASSERT (expr);

If expr is false, the assert outputs information and terminates the execution of the program, and if true, assert does nothing.

Ndebug preprocessing variables

The behavior of an assert depends on the state of a preprocessing variable named Ndebug. If Ndebug is defined, assert does nothing and ndebug is not defined by default.

You can use the # define statement to define NDEBUG, which closes the debug state.

6. Function pointers

The function pointer points to a function, not an object. As with other pointers, the function pointer points to a specific type. The type of the function is determined by its return type and formal parameter type, regardless of the function name.

int func (int A, string s);

The type of the function is int (int, string). To declare a pointer that can point to the function, you only need to substitute the pointer with the letter name.

Int (*p) (int, string)//not initialized

The parentheses of the note:*p must be added

Using function pointers

When the function name is used as a value, the function is automatically converted to a pointer.

Int (*p) (int, string) =func;

You can call the function directly using a function pointer without having to dereference the pointer.

There is no reciprocal conversion between pointers to different function types, and you can assign a value of nullptr and 0 to the function pointer, indicating that the pointer does not point to any function.

pointers to overloaded functions

If you define a pointer to an overloaded function, the compiler uses the pointer type to determine which function to choose, and the pointer type must exactly match one of the overloaded functions.

function pointer parameter

Like arrays, although you cannot define formal parameters for a function type, a parameter can be a pointer to a function. The function can be used directly as an argument, and it is automatically converted to a pointer.

Returns a pointer to a function that uses auto and decltype for function pointer types

Note that when you use Decltype for function names, the function type is returned, not the pointer type, and if you want to represent a function pointer, you need to add *.

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.