Chapter Sixth C + +: Function Basics and Applications

Source: Internet
Author: User
Tags assert

Sixth Chapter function

A function is a named block of code that executes the corresponding code by calling the function.

Function basics

    • The function is executed by invoking the operator (call operator). It is in the form of a pair of parentheses.

    • The invocation of the function completes two tasks (as follows) , at which point the execution of the calling function is temporarily interrupted, and the called function begins execution.

      • Initializes the parameter corresponding to the function with an argument.

      • Transfer control to the tuned function.

    • Return statement:

      • Returns the value in the return statement

      • Move control from the transferred function back to the keynote function

Local objects

    • Name has scope, object has life cycle (Lifetime)

    • Automatic objects (Automatic object): The object is created when the function's control path passes through a variable definition statement, and is destroyed when the end of the block where the definition resides is reached.

    • local Static object : The program execution path is initialized on the first pass of the object definition statement, knowing that the program terminates before it is destroyed.

      • Defines a local variable as static obtained, for example:

        //统计函数count_calls ()被调用了多少次
        size_t count_calls ()
        {
        static size_t ctr = 0; //调用结束后,这个值仍然有效
        return ++ctr;
        }
        int main()
        {
        for (size_t i = 0; i != 10; ++i)
        cout << cout_calls() << endl;
        return 0;
        }

function declaration

    • Also known as function prototypes (Functions Prototype)

    • function three elements ( return type, function name, parameter type ) describe the interface of the function, and the parameter name in the function declaration can be omitted.

    • The function should be declared in the header file, defined in the source file.

    • Split-Compilation

Parameter passing

If the parameter is a reference type, it is bound to the corresponding argument, otherwise, the value of the argument is copied and assigned to the parameter.
-If you do not need to modify the value of a reference parameter, it is best to declare it as a constant reference.

Main: Handling Command-line options

Assuming that the main function is within the executable prog, we can pass the following options to the program:

Prog-d-o ofile data0

These commands are passed to the main function through two optional parameters:

int main (int argc, char *argv[]) {...} Or: int main (int argc, char **argv) {...}

When the argument is passed to the main function, the first element of argv points to the name of the program or an empty string, and the next element passes the arguments provided by the command line at one time. The last pointer will only drop the element value guaranteed to be 0.
-Take the above command behavior example:

ARGC = 5;argv[0] = "prog"; argv[1] = "-D"; argv[2] = "-O"; argv[3] = "ofile"; argv[4] = "data0"; argv[5] = 0;

Functions containing deformable parameters

    • The new C++11 standard provides two ways to write functions that handle different numbers of arguments:

      1. All argument types are the same, and you can pass a standard library type named Initializer_list.

      2. Unlike argument types, we can write a special function called a variadic template.

    • C + + also has a special type of formal parameter: an ellipsis. You can use it to pass a variable number of arguments. This feature is typically used only for interface programs that interact with C functions.

    • initializer_list Formal Parameters

      • Its type is defined in a header file of the same name

      • The following actions are available:

        initializer_list<T> lst; //默认初始化,T类型元素的空列表
        initializer_list<T> lst{a,b,c...};
        //lst的元素数量和初始值一样多;lst的元素是对应初始值的副本;列表中的元素是const
        lst2(lst)
        lst2 = lst //拷贝或复制一个initializer_list对象不会拷贝列表中的元素;拷贝后,原始列表和副本元素共享
        lst.size() //列表中元素的数量
        lst.begin() //返回指向lst中首元素的指针
        lst.end() //返回指向lst中尾元素下一位置的指针

return type and return statement

    • The reference returns an Lvalue, and the other return type gets the right value.

    • list Initialization return value : c++11 The new standard specifies that a function can return a list of values enclosed in curly braces.

The return value of main function main

    • Allow the main function to have no return value (if not, the compiler implicitly inserts return 0)

    • Returning 0 indicates successful execution, and other values depend on the machine.

    • To make the return value machine-Independent, thecstdlib header file defines two preprocessing variables, each of which indicates success and failure:

      return EXIT_FAILURE;
      return EXIT_SUCCESS;
      //因为它们是预处理变量,所以既不能在前面加上std::,也不能在using声明里出现。

Returns an array pointer

    1. Using Type aliases

      typedef int arrT[10]; //arrT是一个类型别名,它表示的类型是含有10个整数的数组
      using arrT = int[10]; //与上一句等价
      arrT* func(int i); //func返回一个指向含有10个整数的数组的指针

    2. Declares a function that returns an array pointer in the following form

      Type (*function(parameter_list)) [dimension]
      //Type表示返回的数组指针指向的数组元素类型
      //dimension表示数组的大小
      //例如:
      int (*func(int i)) [10];

    3. Using the tail return type (C++11)

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

    4. Using Decltype

      int odd[] = {1,3,5,7,9};
      int even[] = {0,2,4,6,8};
      decltype(odd) *arrPtr(int i)
      {
      return (i % 2) ? &odd : &even; //返回一个指向数组的指针
      }

function overloading

If several functions within the same scope have the same name but different parameter lists, we call the overloaded (overloaded) function .

    • No two functions are allowed to be the same except for the return type of all features.

    • overloads and scopes: Once the desired name is found in the current scope, the compiler ignores the entity with the same name in the outer scope.

Special-Purpose language features

Describes the language features related to three functions: default arguments, inline functions, constexpr functions.

Default actual parameters

    • When you call a function that contains a default argument, you can include the argument or omit the argument.

    • Once a parameter has been given a default value, all the parameters that follow it must have a default value.

inline function (inline)

Calling a function is generally slower than finding the value of an equivalent expression, and an inline function avoids the overhead of a function call.
-Specify the function as an inline function, usually by expanding it "inline" on each call point.

constexpr function

    • The return type of the function and all the formal parameter types are literal types.

    • There must be only one return statement in the function.

    • The CONSTEXPR function is implicitly specified as an inline function.

inline functions and constexpr functions are usually defined in the header file

Debugging Help

The program can contain some code for debugging, but the code is only used when developing the program. When the application is written to prepare for publishing, it is necessary to block out the debug code first. This approach uses two preprocessing functions: Assert and Ndebug.

ASSERT preprocessing macros

#include <cassert>assert (expr);//evaluates expr first,//if the expression is false (that is, 0), Assert output information and terminate the execution of the program. If the expression is true (that is, not 0), assert does nothing. For example, a program that operates on a single text may require that a given word is longer than a certain threshold. ASSERT (Word.size () > threshold;

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. Ndebug is not defined by default, and assert will run an execution-time check.

      • The debug state is closed by defining the Ndebug using the # define statement.

      • Many compilers provide command-line options that allow us to define preprocessing variables.

        $ CC -D NDEBUG main.C #微软编译器中用 /D

    • This is only an auxiliary tool for debugging programs, not a substitute for real logic checks, nor is it a substitute for error checking that the program should contain.

    • In addition to assert, you can use Ndebug to write your own conditional debug code:

If Ndebug is defined, the code between the #ifndef和 #endif is ignored void print (const int ia[], aize_t size) {    #ifndef ndebug//_        _func_ _ is a compiler-defined local static variable that holds the name of the function, which is a static array of const char.        Cerr << _ _func_ _ << "array size is" << size << Endl;    #endif}

In addition to _ _ Func _ _, there are four other names:

_ _file_ _ The string literal of the file name _ _line_ _ the integer literal value of the current line number _ _time_ _ the string literal that holds the compilation time of the file _ _data_ _ the string literal that holds the compilation date of the file

function pointers

BOOL Lengthcompare (const string &, const string &);//pf points to a function that has a parameter of two const string and the return value is of type bool. Note that parentheses are essential bool (*PF) (const string &, const string &);    Not initialized

When we use the function name as a value, the function is automatically converted to a pointer

PF = Lengthcompare;     PF points to a function pf named Lengthcompare = &lengthCompare;    The equivalent assignment statement,& is optional

Call this function:

These three calls are equivalent to bool B1 = PF ("Hello", "Goodbye"), bool B2 = (*PF) ("Hello", "Goodbye"), bool B3 = Lengthcompare ("Hello", "Goodbye");

Reference: C++primer Fifth Edition

Related articles:

Fourth C + +: Application of expression concept-operator

The fifth Chapter C + +: Statements related to the introduction

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.