C++c/c++

C++程序 传值和传地址的区别

2019-06-05  本文已影响15人  Joyner2018

程序如下:

#include <iostream>

using namespace std;

//void swap(int a[], int b[])和下面的语句等价

void swap(int a, int b)

{

std::cout<<"call void swap(int a, int b)"<<std::endl;

int temp = a;

a = b;

b = temp;

}

void swap(int *a, int *b)

{

std::cout<<"call void swap(int *a, int *b)"<<std::endl;

int temp = *a;

*a = *b;

*b = temp;

}

int main()

{

int i = 5;

int j = 10;

cout<<"Before swap: i="<<i<<",j="<<j<<endl;

swap(i,j); //-----------------------------------------------------①

cout<<"After the first swap: i="<<i<<",j="<<j<<endl;

swap(&i,&j);// -----------------------------------------------------②

cout<<"After the second swap: i="<<i<<",j="<<j<<endl;

return 1;

}

实验结果为

实验程序结果

分析

1.传值不会改变实参的值,传地址可以改变实参的值。

2.传地址的方式有几种,数组形式和指针形式均可。

3.函数调用完全是模式匹配,调用时实参是地址则配合地址函数,实参是值,则匹配值类型的函数。

上一篇 下一篇

猜你喜欢

热点阅读