这表明,参数值没有被改变,虽然它们已经在函数内部改变。
通过传递函数参数,即是拷贝参数的地址到形式参数的参考方法调用。在函数内部,地址是访问调用中使用的实际参数。这意味着,对参数的更改会影响传递的参数。
要通过引用传递的值,参数的指针被传递给函数就像任何其他的值,所以,相应的,需要声明函数的参数为指针类型如下面的函数互换(),它的交换两个整型变量的值指向它的参数。
/*,function definition 用swap 从而values */func 交换(x * int, y * int), { ,,var temp int ,,temp =, * x ,,,/*,节省,从而value at address x */,,* x =, * y ,,,,,/*, put y into x */,,* y =, temp ,,,/*, put temp into y */}
现在,让我们调用函数互换()通过引用作为在下面的示例中传递数值:
package 主要 import “fmt" func main (), {,,/*, local variable definition */,,, var a int =, 100,,, var b int=, 200 ,,fmt.Printf (“Before 交换,value of a :, % d \ n",, a ),,, fmt.Printf (“Before 交换,value of b :, % d \ n",, b ) ,,/*,calling a function 用swap 从而值只,,*,,a indicates pointer 用a ie只address of variable a 以及,,,*,,b indicates pointer 用b ie只address of variable b只,,*/,,,交换(,,,,b) ,,fmt.Printf (“After 交换,value of a :, % d \ n",, a ),,, fmt.Printf (“After 交换,value of b :, % d \ n",, b )} func 交换(x * int, y * int), {,, var temp int ,, temp =, * x ,,,/*,节省,从而value at address x */,,, * x =, * y ,,,/*, put y into x */,,, * y =, temp ,,,/*, put temp into y */}
让我们把上面的代码放在一个C文件,编译并执行它,它会产生以下结果:
Before 交换,,value of a : 100 Before 交换,value of b : 200 null null