当前位置:网站首页>函数(基本:参数,返回值)
函数(基本:参数,返回值)
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设置为全局变量——不建议。
边栏推荐
- User behavior collection platform
- How to remove installed elpa package
- Get to know MySQL connection query for the first time
- 3. Package the bottom navigation tabbar
- 快手、抖音、视频号交战内容付费
- The new project Galaxy token just announced by coinlist is gal
- Containerd series - detailed explanation of plugins
- Network layer - forwarding (IP, ARP, DCHP, ICMP, network layer addressing, network address translation)
- Ffmepg usage guide
- 学习MVVM笔记(一)
猜你喜欢

Pyqt pyside custom telescopic menu bar sharing (including tutorial)

Use of vscode software

Threejs Internet of things, 3D visualization of factory

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

On the day 25K joined Tencent, I cried

Special Edition: spreadjs v15.1 vs spreadjs v15.0

mxnet导入报各种libcudart*.so、 libcuda*.so找不到

Is "golden nine and silver ten" the best time to find a job? Not necessarily

Uni app change the default component style
随机推荐
NetSetMan pro (IP fast switching tool) official Chinese version v5.1.0 | computer IP switching software download
基于TCP的移动端IM即时通讯开发仍然需要心跳保活
Threejs loads the city obj model, loads the character gltf model, and tweetjs realizes the movement of characters according to the planned route
我国算力规模排名全球第二:计算正向智算跨越
Fuel consumption calculator
[thingsboard] how to replace the homepage logo
Network layer - forwarding (IP, ARP, DCHP, ICMP, network layer addressing, network address translation)
[untitled]
Hexadecimal to octal
行为感知系统
This is an age of uncertainty
Convert Boolean to integer value PHP - Convert Boolean to integer value PHP
Interview related high-frequency algorithm test site 3
网络安全-记录web漏洞修复
Threejs realizes the drawing of the earth, geographical location annotation, longitude and latitude conversion of world coordinates threejs coordinates
provide/inject
[brush questions] BFS topic selection
Hexadecimal to decimal
Uni app change the default component style
[finebi] the process of making custom maps using finebi