在函数的第一眼

一个函数是一个序列的设计做一个特定工作表。你已经知道,每个程序都必须有一个功能叫做main()。然而大多数程序有许多功能,他们所有的工作类似于

通常,你的程序需要打断它是什么做的临时做其他的事情。你在现实生活中所有的时间。例如,你可能读一本书时,你记得你需要打一个电话。你把一个书签在你的书中,打电话你完成的电话你回到你的书你离开的地方

C++程序的工作方式相同。一个程序将执行语句顺序在一个函数在遇到函数调用时。一个函数调用是一个表达式,告诉CPU中断当前的功能和执行另一个函数。该CPU”把书签”在当前执行点,然后调用(执行)在函数调用中指定的功能。调用函数终止,CPU回到点的书签继续执行

下面是一个示例程序,展示了如何函数的声明调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
 
// Declaration of function DoPrint()
void DoPrint()
{
    using namespace std;  // we need this in each function that uses cout and endl
    cout << "In DoPrint()" << endl;
}
 
// Declaration of main()
int main()
{
    using namespace std;  // we need this in each function that uses cout and endl
    cout << "Starting main()" << endl;
    DoPrint(); // This is a function call to DoPrint()
    cout << "Ending main()" << endl;
    return 0;
}


程序产生的输出如下

main()

doprint()

结束main()

这个程序开始执行在main()顶部,和第一行被执行打印起始main()。在主要的第二行是一个函数调用doprint。在这一点上,main()语句执行暂停,和CPU跳doprint()。第一个(也是唯一的)在doprint打印在doprint()线。当doprint()终止,调用者(main())继续执行它离开的地方。因此主要的打印结束main()执行下一个语句

函数可以被多次调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
 
// Declaration of function DoPrint()
void DoPrint()
{
     using namespace std;
     cout << "In DoPrint()" << endl;
}
 
// Declaration of main()
int main()
{
     using namespace std;
     cout << "Starting main()" << endl;
     DoPrint(); // This is a function call to DoPrint()
     DoPrint(); // This is a function call to DoPrint()
     DoPrint(); // This is a function call to DoPrint()
     cout << "Ending main()" << endl;
     return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值