C/C++.参数传递的方式及比较 值传递、指针传递、引用传递

引用传递是C++的新特性,在C中会编译出错,重点注意。

 
 /* 
 	参数传递的方式及比较
 	值传递、指针传递、引用传递
 */
 
 #include "stdafx.h"
 #include <stdio.h>
 //值传递
10 void swap1(int p,int q)
11 {
12     int temp;
13     temp=p;
14     p=q;
15     q=temp;
16 }
17 
18 //指针传递,函数体内只有指针值的变化
 void swap2(int *p,int *q)
20 {`在这里插入代码片`
21     int temp;
22     temp=*p;
23     *p=*q;
24     *q=temp;
25 }
26 
27 //指针传递,函数体内只有指针的变化
28 void swap3(int *p,int *q)
29 {
30     int *temp;
31     temp=p;
32     p=q;
33     q=temp;
34 }
35 
36 //引用传递
37 void swap4(int &p,int &q)
38 {
39     int temp;
40     temp=p;
41     p=q;
42     q=temp;
43 }
44 
45 int main()
46 { 
47     int a=1,b=2;
48     swap1(a,b);
49     //swap2(&a,&b);
50     //swap3(&a,&b);
51     //swap4(a,b);
52     cout<<a<<"  "<<b<<endl;
53     return 0;
54 }

猜你喜欢

转载自blog.csdn.net/qq_38916259/article/details/88052444