2019年3月8日 星期五

C/C++ 函數參數的範例

此文舉例幾個, 整數型態的變數
代入至副函數時, 其參數有幾種型態

還有陣列直接代入副函數的例子

#include <iostream>

using namespace std;

/* 參數為 變數  , 填入值即可,
 * 和原本的資料沒有直接關係
 */
int swap(int x, int y)
{
int temp;
temp = x;
x = y ;
y = temp ;
}

/* 參數為 指標變數 , 指標變數的功能是 指向一個地址,
 * 要使用此函數時必須填入地址
 */
int swap_ptr(int *x, int *y)
{
int temp;
temp = *x;
*x = *y ;
*y = temp ;
}

/* 參數為 取址變數 , 取址變數的功能是 取參數1的地址,
 * 取參數2的地址, 會直接改變結果
 */
int swap_ref(int &x, int &y)
{
int temp;
temp = x;
x = y ;
y = temp ;
}

int showArray(int *array)
{
for(int i = 0; i < 5; i++)
{
cout << array[i] << " "  ;
}
cout << endl ;
}


void S0805(void)
{
int x = 10, y = 15;
int *ptr_x = &x, *ptr_y = &y;
int varArray[5]  = {1,5,2,4,3};

// 因為陣列本身就是一個指標變數 , 他是由數個 char 的位址組織起來的,
// 故可以直接代入函數
showArray(varArray);

swap(x,y);
printf("%x, %x\n", ptr_x,ptr_y);
swap_ptr(ptr_x, ptr_y);

swap_ref(x,y);
cout << x << "," << y << endl;

}
輸出結果如下:


沒有留言:

張貼留言

Android Studio IDE 錯誤

 :app:compile xxxxx JavaWithJavac FAILED An exception has occurred in the compiler (1.8.0_312). Please file a bug against the Java compiler ...