Macros são uma das minhas ferramentas favoritas nas linguagens C e C ++. Pessoas inteligentes e livros inteligentes aconselham evitar o uso de macros tanto quanto possível, substituindo-as por modelos, constantes e funções inline sempre que possível e por um bom motivo. Usando macros, você pode criar não apenas um código elegante, mas também produzir bugs igualmente elegantes, que serão muito difíceis de detectar e corrigir. Mas se você seguir algumas regras simples ao trabalhar com macros, elas se tornarão uma arma poderosa que não atira em seus próprios joelhos. Mas primeiro, vamos descobrir o que exatamente são macros em C e C ++?
O que são macros?
++ , . , . , #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). , .