Macros are one of my favorite tools in the C and C ++ languages. Smart people and smart books advise to avoid using macros as much as possible, replacing them with templates, constants and inline functions whenever possible, and for good reason. Using macros, you can create not only elegant code, but also produce equally elegant bugs, which will then be very difficult to catch and fix. But if you follow a few simple rules when working with macros, they become a powerful weapon that does not shoot in your own knees. But first, let's figure out what exactly are macros in C and C ++?
What are 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). , .