C 傳值方式調(diào)用函數(shù)

C 函數(shù) C 函數(shù)

向函數(shù)傳遞參數(shù)的傳值調(diào)用方法,把參數(shù)的實(shí)際值復(fù)制給函數(shù)的形式參數(shù)。在這種情況下,修改函數(shù)內(nèi)的形式參數(shù)不會(huì)影響實(shí)際參數(shù)。

默認(rèn)情況下,C 語言使用傳值調(diào)用方法來傳遞參數(shù)。一般來說,這意味著函數(shù)內(nèi)的代碼不會(huì)改變用于調(diào)用函數(shù)的實(shí)際參數(shù)。函數(shù) swap() 定義如下:

/* 函數(shù)定義 */
void swap(int x, int y)
{
   int temp;

   temp = x; /* 保存 x 的值 */
   x = y;    /* 把 y 賦值給 x */
   y = temp; /* 把 temp 賦值給 y */
  
   return;
}

現(xiàn)在,讓我們通過傳遞實(shí)際參數(shù)來調(diào)用函數(shù) swap()

#include <stdio.h>
 
/* 函數(shù)聲明 */
void swap(int x, int y);
 
int main ()
{
   /* 局部變量定義 */
   int a = 100;
   int b = 200;
 
   printf("交換前,a 的值: %d\n", a );
   printf("交換前,b 的值: %d\n", b );
 
   /* 調(diào)用函數(shù)來交換值 */
   swap(a, b);
 
   printf("交換后,a 的值: %d\n", a );
   printf("交換后,b 的值: %d\n", b );
 
   return 0;
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

交換前,a 的值: 100
交換前,b 的值: 200
交換后,a 的值: 100
交換后,b 的值: 200

上面的實(shí)例表明了,雖然在函數(shù)內(nèi)改變了 a 和 b 的值,但是實(shí)際上 a 和 b 的值沒有發(fā)生變化。

C 函數(shù) C 函數(shù)