Chapter 6 Function
A function is a named block of code that executes the corresponding code by calling the function.
Execute the function bycall operator(call operator). Its form is a pair of parentheses.
The call of the function completes two tasks (as follows). At this time, the execution of themain calling function(calling function) is temporarily interrupted, and the called function (called function) )Begin execution.
Initialize the formal parameters corresponding to the function with actual parameters.
Transfer control to the called function.
return statement:
Return the value in the return statement
Move control from the called function back to the calling function
Names have scope, objects haveLifecycle(lifetime)
Automatic object(automatic object): This object is created when the control path of the function passes through the variable definition statement. Destroy it when the end of the block in which it is defined is reached.
Local static object: It is initialized when the program execution path passes through the object definition statement for the first time, and is not destroyed until the program terminates.
Define local variables asstaticto obtain, for example:
//Statistical function count_calls () How many times has it been called
size_t count_calls ()
{
static size_t ctr = 0; //After the call is completed, this value is still valid
return ctr;
}
int main ()
{
for (size_t i = 0; i != 10; i)
cout << cout_calls() << endl;
return 0;
}
Also calledfunction prototype(function prototype)
The three elements of a function (return type, function name, formal parameter type) describe the interface of the function, and the formal parameter name can be omitted in the function declaration.
Functions should be declared in the header file and defined in the source file.
Separate compilation
If the formal parameter is a reference type, it will be bound to the corresponding actual parameter; otherwise, copy the value of the actual parameter and assign it to the formal parameter.
- If the value of a reference parameter does not need to be modified, it is best to declare it as a constant reference.
Assuming that the main function is located in the executable file prog, we can pass the following options to the program:
prog -d -o ofile data0
These commands pass two executable files The selected formal parameters are passed to the main function:
int main(int argc, char *argv[]) {...} //或: int main(int argc, char **argv) {...}
When the actual parameters are passed to the main function, the first element of argv points to the name of the program or an empty string, and the next elements are passed to the command line at a time actual parameters. The last pointer will only drop the element value and is guaranteed to be 0.
- Take the above command line as an example:
argc = 5;argv[0] = "prog";argv[1] = "-d";argv[2] = "-o";argv[3] = "ofile";argv[4] = "data0";argv[5] = 0;
C 11 new standard provides two methods to write functions that can handle different numbers of instances Parameter function:
All actual parameters are of the same type, and a standard library type named initializer_list can be passed.
If the actual parameter types are different, we can write a special function called a variable parameter template.
#C There is also a special parameter type: ellipsis. You can use it to pass a variable number of actual parameters. This function is generally only used for interface programs that interact with C functions.
initializer_list formal parameter
The type is defined in the header file with the same name
Provides the following operations:
initializer_list
initializer_list
//lst has the same number of elements as the initial value; the elements of lst are copies of the corresponding initial values; the elements in the list are const
lst2(lst)
lst2 = lst //Copying or copying an initializer_list object will not copy the elements in the list; after copying, the original list and the copy elements are shared
lst.size() //The number of elements in the list
lst.begin( ) //Returns a pointer to the first element in lst
lst.end() //Returns a pointer to the next position of the last element in lst
References return lvalues, and other return types get rvalues.
List initialization return value: The new C 11 standard stipulates that a function can return a list of values surrounded by curly braces.
Allows the main function to have no return value (if not, the compiler implicitly inserts return 0)
返回0表示执行成功,其他值依机器而定。
为了使返回值与机器无关,cstdlib头文件定义了两个预处理变量,分别表示成功和失败:
return EXIT_FAILURE;
return EXIT_SUCCESS;
//因为它们是预处理变量,所以既不能在前面加上std::,也不能在using声明里出现。
使用类型别名
typedef int arrT[10]; //arrT是一个类型别名,它表示的类型是含有10个整数的数组
using arrT = int[10]; //与上一句等价
arrT* func(int i); //func返回一个指向含有10个整数的数组的指针
声明一个返回数组指针的函数,形式如下
Type (*function(parameter_list)) [dimension]
//Type表示返回的数组指针指向的数组元素类型
//dimension表示数组的大小
//例如:
int (*func(int i)) [10];
使用尾置返回类型(C++11)
auto func(int i) -> int(*)[10];
使用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; //返回一个指向数组的指针
}
如果同一作用域内的几个函数名字相同但形参列表不同,我们称之为重载(overloaded)函数。
不允许两个函数除了返回类型外其他所有要素都相同。
重载与作用域:一旦在当前作用域中找到了所需的名字,编译器就会忽略掉外层作用域中的同名实体。
介绍三种函数相关的语言特性:默认实参、内联函数、constexpr函数。
调用包含默认实参的函数时,可以包含该实参,也可以省略该实参。
一旦某个形参被赋予了默认值,它后面所有的形参都必须有默认值。
调用函数一般比求等价表达式的值要慢,内联函数可避免函数调用的开销。
- 将函数指定为内联函数,通常就是将它在每个调用点上“内联地”展开。
函数的返回类型和所有的形参类型都得是字面值类型。
函数中必须有且只有一条return语句。
constexpr函数被隐式地指定为内联函数。
程序可以包含一些用于调试的代码,但这些代码只在开发程序时使用。当应用程序编写完成准备发布时,要先屏蔽掉调试代码。这种方法用到两项预处理功能:assert和NDEBUG。
#includeassert(expr);//首先对expr求值,//如果表达式为假(即0),assert输出信息并终止程序的执行。//如果表达式为真(即非0),assert什么也不做。//例如:对一个文本进行操作的程序可能要求所给定单词的长度都大于某个阈值。assert(word.size() > threshold;
assert的行为依赖于一个名为NDEBUG的预处理变量的状态。如果定义了NDEBUG,则assert什么也不做。默认状态下没有定义NDEBUG,此时assert将运行执行时检查。
使用#define语句定义NDEBUG,从而关闭调试状态。
很多编译器都提供了命令行选项使我们可以定义预处理变量。
$ CC -D NDEBUG main.C #微软编译器中用 /D
这只是调试程序的辅助手段,不能代替真正的逻辑检查,也不能代替程序本应该包含的错误检查。
除了assert以外,也能使用NDEBUG编写自己的条件调试代码:
//如果定义了NDEBUG,#ifndef和#endif之间的代码将被忽略void print(const int ia[], aize_t size) { #ifndef NDEBUG //_ _func_ _是编译器定义的一个局部静态变量,用于存放函数的名字,它是const char的一个静态数组。 cerr << _ _func_ _ << "array size is " << size << endl; #endif}
除了_ _func_ _之外,还有其它四个名字:
_ _FILE_ _ 存放文件名的字符串字面值 _ _LINE_ _ 存放当前行号的整型字面值 _ _TIME_ _ 存放文件编译时间的字符串字面值 _ _DATA_ _ 存放文件编译日期的字符串字面值
bool lengthCompare(const string &, const string &);//pf指向一个函数,该函数的参数是两个const string的引用,返回值是bool类型。注意圆括号必不可少bool (*pf) (const string &, const string &); //未初始化
当我们把函数名作为值使用时,该函数自动地转换成指针
pf = lengthCompare; //pf指向名为lengthCompare的函数pf = &lengthCompare; //等价赋值语句,&是可选的
调用该函数:
//此三个调用等价bool b1 = pf("hello", "goodbye");bool b2 = (*pf)("hello", "goodbye");bool b3 = lengthCompare("hello", "goodbye");
参考:C++Primer第五版
相关文章:
Chapter 5C: Introduction to statements
The above is the detailed content of Chapter 6 C++: Function Basics and Applications. For more information, please follow other related articles on the PHP Chinese website!