当前位置:网站首页>形参、局部变量以及局部静态变量
形参、局部变量以及局部静态变量
2022-04-22 05:44:00 【What’smean】
形参和定义在函数体内部的变量统称为局部变量,它们对函数而言是局部的,仅在函数的作用域内可见。函数体内的局部变量又分为普通局部变量和静态局部变量,对于形参和普通局部变量来说,当函数的控制路径经过变量定义语句时创建该对象,当到达定义所在的块末尾时销毁它。我们把只存在于块执行期间的对象称为自动对象。这几个概念的区别是:
- 形参是一种自动对象,函数开始时为形参申请内存空间,我们用调用函数时提供的实参初始化形参对应的自动对象。
- 普通变量对应的自动对象也容易理解,我们在定义该变量的语句处创建自动对象,如果定义语句提供了初始值,则用该值初始化;否则,执行默认初始化。当该变量所在的块结束后,变量失效。
- 局部静态变量比较特殊,它的生命周期贯穿函数调用及之后的时间。局部静态变量对应的对象称为局部静态对象,它的生命周期从定义语句处开始,直到程序结束才终止。
代码助解:
#include<iostream>
using namespace std;
double myAdd(double val1,double val2){
double resul = val1+val2;
static unsigned iCnt = 0;//静态局部变量(贯穿程序始终)
++iCnt;
cout<<"该函数共执行了"<<iCnt<<"次"<<endl;
return resul;
}
int main(){
double num1,num2; //普通局部变量
cout<<"请输入两个数:"<<endl;
while(cin>>num1>>num2){
cout<<"求和结果为:"<<myAdd(num1,num2)<<endl;
}
return 0;
}
输出结果:
请输入两个数:
2.4
3.4
该函数共执行了1次
求和结果为:5.8
33
33
该函数共执行了2次
求和结果为:66
43
34
该函数共执行了3次
求和结果为:77
^Z
请按任意键继续. . .
版权声明
本文为[What’smean]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_42492218/article/details/124290570
边栏推荐
- Binary search and its classical applications (left boundary, right boundary, etc.)
- 关于手眼标定中RT矩阵的欧拉角和Halcon中pose的类型之间的关系
- jeecgboot-online錶單開發-控件配置
- opencv近期学习测试代码
- 二分查找及其经典应用(左边界,右边界等)
- opencv代码
- Setting time and date display of QT learning
- Part 84 leetcode sword refers to offer dynamic programming (I) Fibonacci sequence
- Can data frame, remote frame, error frame, and error reconnection
- DS18B20 of Blue Bridge Cup embedded expansion board learning
猜你喜欢

Calibration principle of robot tool coordinate system

Installation of QT learning

Chapter 89 leetcode refers to offer dynamic programming (6) translating numbers into strings

I/O多路复用(select/poll/epoll)

Blue Bridge Cup embedded expansion board learning nixie tube

Daily learning record -- solving graphviz Chinese garbled code problem

蓝桥杯嵌入式扩展板学习之DHT11

Record the pit of ad software learning

Characteristics and usage of QT signal and slot

关于手眼标定中RT矩阵的欧拉角和Halcon中pose的类型之间的关系
随机推荐
QWbEngneView和QWebChanel的使用。
判断完全二叉树
wgs84坐标转换,地图拾取wgs84坐标工具推荐
机器人抓取物体原理初步
Speed measurement based on 51 single chip microcomputer and Hall sensor
jeecgboot-online在线开发3
deep learning object detection 精选
汇编 makefile
Blue Bridge Cup embedded expansion board learning nixie tube
初识数据链表
Record one installation of centos8 + postgresql9 6 + PostGIS's painful experience
Part 74 leetcode exercise (VII) 7 Integer inversion
图像金字塔、边缘检测、图像加权显示、直方图均衡化
Compiling OpenSSL on HP UNIX and using
jeecgboot-online表单开发-控件配置
ADC
VB operation, Excel format setting and printing page setting (Simplified)
qt中ShellExecute、ShellExecuteEx和WinExec的用法和区别
c#委托、线程、定时器学习感悟
Chapter 86 leetcode refers to offer dynamic programming (III) maximum profit of stock