語法書 / AA 競程語法書 上冊 / 第七單元 / 本單元語法速查表

本單元語法速查表

語法 / 關鍵字 用途 範例
回傳型 函式名(參數) 定義函式 int add(int x, int y) { return x + y; }
return 值; 回傳值並結束函式 return x + y;
void 函式名() 定義不回傳值的函式 void print() { cout << "Hi\n"; }
函式名(參數) 呼叫函式 add(3, 5)
巢狀呼叫 呼叫結果當參數再呼叫 f(f(2))gcd(gcd(x, y), z)
bool 函式名(參數) 判斷函式,直接回傳條件 bool isOdd(int x) { return x % 2 != 0; }
mainreturn 0; 提早結束整個程式 if (n == 0) { cout << 0; return 0; }
型 &參數 Pass by reference void modify(int &x) { x = 10; }
#include<algorithm> 引入 swap, max, min swap(a, b)max(a, b)
#include<numeric> 引入 gcd, lcm(lcm 大數用 long long 參數) gcd(12, 8)
static 型 變數 靜態變數(值跨函式呼叫保留) static int count = 0; count++;
參數 = 預設值 設定預設參數 int func(int x = 5)