# call by value call by address call by

• Slides: 43

call by value? call by address (或 call by pointer)? call by reference? • • • Call by value: swap(int a, int b) Call by address: swap(int* a, int* b) Call by reference: swap (int &a, int &b)

Call by value: swap(int a, int b) void swap(int a, int b){ int tmp = a; a = b; b = tmp; } • 呼叫swap(x, y)後，x和y的值並不會有變化。

int g_int = 0; void change. Ptr(int* p. Int){ p. Int = &g_int; } void main(){ int local. Int = 1; int* local. PInt = &local. Int; change. Ptr(local. PInt); printf("%dn", *local. PInt); } 1. 印出來的數字仍然會是local. Int的1 1. 因為chang. Ptr中的p. Int是由local. PInt「複製」 過去的，對p. Int做改變並不會反映到local. PInt 身上。

pointer to pointer int g_int = 0; void change. Ptr(int** p. Int){ *p. Int = &g_int; } void main(){ int local. Int = 1; int* local. PInt = &local. Int; change. Ptr(&local. PInt); printf("%dn", *local. PInt); } g_int 0 local. Int 1 local. PInt

pointer to pointer int g_int = 0; void change. Ptr(int** p. Int){ *p. Int = &g_int; } void main(){ int local. Int = 1; int* local. PInt = &local. Int; change. Ptr(&local. PInt); printf("%dn", *local. PInt); } g_int 0 local. Int 1 local. PInt p. Int

pointer to pointer int g_int = 0; void change. Ptr(int** p. Int){ *p. Int = &g_int; } void main(){ int local. Int = 1; int* local. PInt = &local. Int; change. Ptr(&local. PInt); printf("%dn", *local. PInt); } g_int 0 local. Int 1 local. PInt *p. Int

reference to pointer • 同樣的功能也可以用「指標的參考」來做 int g_int = 0; void change. Ptr(int* &ref. PInt){ ref. PInt = &g_int; } void main(){ int local. Int = 1; int* local. PInt = &local. Int; change. Ptr(local. PInt); printf("%dn", *local. PInt); }

reference to pointer int g_int = 0; void change. Ptr(int* &ref. PInt){ ref. PInt = &g_int; } void main(){ int local. Int = 1; int* local. PInt = &local. Int; change. Ptr(local. PInt); printf("%dn", *local. PInt); } g_int 0 local. Int 1 local. PInt

reference to pointer int g_int = 0; void change. Ptr(int* &ref. PInt){ ref. PInt = &g_int; } void main(){ int local. Int = 1; int* local. PInt = &local. Int; change. Ptr(local. PInt); printf("%dn", *local. PInt); } g_int 0 local. Int 1 ref. PInt即local. PInt

reference to pointer int g_int = 0; void change. Ptr(int* &ref. PInt){ ref. PInt = &g_int; } void main(){ int local. Int = 1; int* local. PInt = &local. Int; change. Ptr(local. PInt); printf("%dn", *local. PInt); } g_int 0 local. Int 1 ref. PInt即local. PInt