マクロは、CおよびC ++言語で私のお気に入りのツールの1つです。賢い人や賢い本は、マクロの使用をできるだけ避け、可能な限り、そして正当な理由で、マクロをテンプレート、定数、インライン関数に置き換えることをお勧めします。マクロを使用すると、洗練されたコードを作成できるだけでなく、同様に洗練されたバグを生成することもできます。バグを見つけて修正するのは非常に困難です。しかし、マクロを操作するときにいくつかの簡単なルールに従うと、マクロは自分の膝を撃たない強力な武器になります。しかし、最初に、CおよびC ++のマクロとは正確に何であるかを理解しましょう。
マクロとは何ですか?
++ , . , . , #include, #pragma, #if . #define.
#define:
#define PI 3.14159
, , PI :
double area = 2 * PI * r * r;
, , :
double area = 2 * 3.14159 * r * r;
PI - , . , . .
// :
PI = 3; // : 3.14159 = 3
int *x = Π // : int *x = &3.14159
, , , , "". , :
#undef PI
PI .
, . , . - , :
#define MAX(a, b) a >= b ? a : b
. , :
#define SWAP(type, a, b) type tmp = a; a = b; b = tmp;
, :
SWAP(int, num1, num2)
SWAP(float, num1, num2)
, , typeof C decltype C++. tmp , :
#define SWAP(a, b) decltype(a) tmp = a; a = b; b = tmp;
, , , '\':
#define SWAP(a, b) \
decltype(a) tmp = a; \
a = b; \
b = tmp;
, '#':
#define PRINT_VAL(val) printf("Value of %s is %d", #val, val);
int x = 5;
PRINT_VAL(x) // -> Value of x is 5
- , . , , '##':
#define PRINT_VAL (number) printf("%d", value_##number);
int value_one = 10, value_two = 20;
PRINT_VAL(one) // -> 10
PRINT_VAL(two) // -> 20
, .
1. .
MAX. , :
int x = 1, y = 5;
int max = MAX(++x, --y);
, :
int max = ++x >= --y ? ++x : --y;
max 4, , 3. , . , - . , .
2. .
MAX. , - ?
int result = 5 + MAX(1, 4);
, result 9, :
int result = 5 + 1 > 4 ? 1 : 4;
result 1. , MAX :
#define MAX(a, b) ((a) >= (b) ? (a) : (b))
.
3. .
, :
#define MACRO() doSomething(); \
doSomethinElse();
:
if (some_condition) MACRO()
:
if (some_condition) doSomething();
doSomethinElse();
, if , . , , . do {} while (0); .
#define MACRO() do { \
doSomething(); \
doSomethingElse(); \
} while(0)
, . , , , , , , , MACRO() . , .
if (some_condition) MACRO();
. - :
#define DEF_SUM(type) type sum_##type (type a, type b) { \
type result = a + b; \
return result; \
}
, :
DEF_SUM(int)
DEF_SUM(float)
DEF_SUM(double)
int main() {
sum_int(1, 2);
sum_float(2.4, 6,3);
sum_double(1.43434, 2,546656);
}
++. , , , long long unsigned short, (sum_##type). , .