C++按值传递和传递按址

#include<iostream>
using namespace std;
void swap1(int a, int b) {   /*按值传递,复制了原来的值,不会改变原来的值*/
int tmp = a;
a = b;
b = tmp;
}
void swap2(int* a, int* b) {/*传递指针*/
int tmp = *a;
*a = *b;
*b = tmp;
}
void swap3(int& a, int& b) {/*传递引用*/
int tmp = a;
a = b;
b = tmp;
}
void swap4(int **p1, int **p2) {/*传递二级指针*/
int *tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void main() {
int a = 1;  int b = 2;
swap1(a, b);
printf("a=%d b=%d \n", a, b);  /*a=1,b =2*/
int c = 1;  int d = 2;
swap2(&c, &d);                 
printf("c=%d d=%d \n", c, d);   /*a=2,b=1*/
int e = 1;  int f = 2;
swap3(e, f);                
printf("e=%d f=%d \n", e, f);   /*e=2,f=1*/
int g = 1;  int h = 2;
int *gp = &g;
int *gh = &h;
swap4(&gp, &gh);   
printf("e=%d f=%d \n", *gp, *gh);   /*g=2,h=1*/
system("pause");
}


猜你喜欢

转载自blog.csdn.net/qq_28816195/article/details/78083079