当前位置:网站首页>函数(基本:参数,返回值)
函数(基本:参数,返回值)
2022-07-05 04:16:00 【曹乐乐爱学习】
函数参数传递:
A-函数的值传递:
void fun(int a,int b);//函数声明(函数原型)
就是实参赋值给形参,在函数处理中,实参本身是不受影响的。例:
实现两个数据交换:
void swap(int ,int );
void swap(int num1,int num2)
{
int n1,n2,t;t =n1;
n1 = n2;
n2 = t;
}

原因:实参a,b传递给形参n1,n2的只是数值,而,a与n1根本就不是同一个地址空间,所以无论n1,n2如何操作,根本对a,b产生不了任何影响。

如果要解决这个问题,2种方式:
1、使用全局变量—— 不建议,因为函数尽量要模块化,尽量减少数据之间互相影响。(所谓的:高内聚,低耦合?)
2、地址传递(指针传递)——建议
只说2、地址传递:
B-函数地址传递:

这样以来,直接把a,b的地址传递进来,进行操作;实质上就是对a,b本身进行操作(说的好像是屁话)。
附加:(为了安全起见,有些时候,我们传地址,也并不是为了修改原始数据,那么可以使用const 修饰一下,只读)
比如求字符串长度:

函数的返回值
如上图,函数内求了字符串长度之后,我还需要把求得的值,传递到主函数去使用。两种方法:
1、使用全局变量——不建议
2、使用函数返回值
函数的返回值

但是要注意:

我只是加了一句,打印返回的n的值,就报错?
这是因为:函数中如果使用auto存储类型(默认不写),生命周期只存在于函数被调用期间(局部变量是放到栈上的),在函数执行完毕之后,就会释放,不能再被访问了,如果进行读写,就是非法。
而return n 之后,把函数直接赋值给变量却没问题,是因为:return的值,就是函数本身的返回值。
如果想打印出n的值,还是上面1所描述的方法:将n设置为全局变量——不建议。
边栏推荐
- Open graph protocol
- EasyCVR平台出现WebRTC协议视频播放不了是什么原因?
- Use Firefox browser to quickly pick up Web image materials
- Pyqt5 displays file names and pictures
- This is an age of uncertainty
- Uni app common functions /api
- How to realize real-time audio and video chat function
- Interview related high-frequency algorithm test site 3
- 根据入栈顺序判断出栈顺序是否合理
- lds链接的 顺序问题
猜你喜欢

On the day 25K joined Tencent, I cried

Online text line fixed length fill tool

Uni app change the default component style

3. Package the bottom navigation tabbar

Network layer - forwarding (IP, ARP, DCHP, ICMP, network layer addressing, network address translation)

如何优雅的获取每个分组的前几条数据

快手、抖音、视频号交战内容付费
![[phantom engine UE] package error appears! Solutions to findpin errors](/img/d5/6747e20da6a8a4ca461094bd27bbf0.png)
[phantom engine UE] package error appears! Solutions to findpin errors

C language course setting: cinema ticket selling management system

“金九银十”是找工作的最佳时期吗?那倒未必
随机推荐
[illusory engine UE] method to realize close-range rotation of operating objects under fuzzy background and pit recording
【虚幻引擎UE】实现背景模糊下近景旋转操作物体的方法及踩坑记录
如何优雅的获取每个分组的前几条数据
MySQL: view with subquery in the from clause limit
Threejs realizes the drawing of the earth, geographical location annotation, longitude and latitude conversion of world coordinates threejs coordinates
What is the reason why the webrtc protocol video cannot be played on the easycvr platform?
Rust blockchain development - signature encryption and private key public key
Wechat applet development process (with mind map)
机器学习 --- 决策树
基于TCP的移动端IM即时通讯开发仍然需要心跳保活
Study notes 7
About the project error reporting solution of mpaas Pb access mode adapting to 64 bit CPU architecture
[understand series after reading] 6000 words teach you to realize interface automation from 0 to 1
About the recent experience of writing questions
北京程序员的真实一天!!!!!
lds链接的 顺序问题
EasyCVR平台出现WebRTC协议视频播放不了是什么原因?
[phantom engine UE] the difference between running and starting, and the analysis of common problems
On the day 25K joined Tencent, I cried
Clickpaas low code platform