106年地方特考四等程式設計概要
四、試問下列 C++ 程式碼逐一執行後,Value 與 list 輸出結果各為多少?(25 分) void swap_ref(int &a, int &b) { int temp; temp = a; a = b; b = temp; } void swap(int a, int b) { int temp; swap_ref(a, b); temp = a; a = b; b = temp; } void main( ) { int Value = 5, list[3] = {1, 2, 3}; swap(Value+list[2]++, ++list[0]); swap_ref(list[0], ++list[2]); } |
答:
#include <iostream> using namespace std; void swap_ref(int& a, int& b) { int temp; temp = a; a = b; b = temp; } void swap(int a, int b) { int temp; swap_ref(a, b); temp = a; a = b; b = temp; } void main( ) { int Value = 5, list[3] = { 1, 2, 3 }; swap(Value + list[2]++, ++list[0]); swap_ref(list[0], ++list[2]); cout << "Value = " << Value << endl; for (int i = 0; i < 3; i++) { cout << "list[" << i << "] = " << list[i] << endl; } } |
執行結果:
Value = 5
list[0] = 5
list[1] = 2
list[2] = 2
說明:
int Value = 5, list[3] = { 1, 2, 3 };
list陣列:
0 |
1 |
2 |
1 |
2 |
3 |
1.呼叫 swap(Value + list[2]++, ++list[0]):
++list[0] = list[0]+1 = 1+1 = 2
Value+list[2] = 5+3 = 8
swap(8, 2)
呼叫 void swap_ref(int& a, int& b) => void swap_ref(8, 2)
a = 2, b = 8
回到 swap(Value + list[2]++, ++list[0])
因為是傳值呼叫,所以不會影響 Value 和 list 的值。
list[2]++ = list[2]+1 = 3+1 = 4
list陣列:
0 |
1 |
2 |
2 |
2 |
4 |
2.呼叫 swap_ref(list[0], ++list[2]):
list[0] = 2
list[2] = list[2]+1 = 4+1 = 5
swap_ref(2, 5)
a = 5, b = 2
回到 swap_ref(list[0], ++list[2])
因為是傳址呼叫,所以會影響 Value 和 list 的值。
list[0] = 5, list[2] = 2
list陣列:
0 |
1 |
2 |
5 |
2 |
2 |