What are they for and how to use them?
3 answers
# placed before the macro argument turns it into a string. For example, the code:
#define QUOTE(a) #a int main() { cout << QUOTE(2 + 2) << " = " << 4 << endl; }
after the preprocessor work will turn into
int main() { cout << "2 + 2" << " = " << 4 << endl; }
A useful example of use is the ASSERT debug macro. Example of implementation:
#define ASSERT(c) \ if (!c) { \ std::cerr << "Assertion failed in " << __FILE__ \ << "(line " << __LINE__ << ") : " << #c << std::endl; \ exit(1); \ }
If you give it a false condition to it, for example ASSERT (2 * 2! = 4), then it will output something like:
Assertion failed in test.cpp(line 12) : 2 * 2 != 4
and complete the program.
## is needed to peck macro arguments with other parts of the macro or with each other. It is rarely used, mainly for code generation. Wikipedia example:
#define MYCASE(item,id) \ case id: \ item##_##id = id;\ break switch(x) { MYCASE(widget,23); }
After preprocessing turns into:
switch (x) { case 23: widget_23 = 23; break; }
At the beginning of the line, # means the actual beginning of the preprocessor directive. In the middle of a directive, this is what it means. The fact is that if the macro is inside the quotation marks, no replacement is made. If we need to enclose a macro change in quotes, we can write:
#define macro(a) puts(#a)
Line
macro (text);
will be deployed like this
puts ("text");
Two ## signs will produce, when deployed, a concatenation of the actual macro parameters:
#define macro(a, b) a##b macro (name, 1)
unfold in
name1
See K & R ch. 4.11.2
Something like this .
Preprocessor directives:
#define CONSTANT value //ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΠΊΠΎΠ½ΡΡΠ°Π½ΡΡ #include file_name //Π²ΠΊΠ»ΡΡΠ΅Π½ΠΈΠ΅ Π² ΠΏΡΠΎΠ΅ΠΊΡ ΡΠ°ΠΉΠ»Π° file_name #pragma option //Π·Π°Π΄Π°Π΅ΠΌ ΠΌΠ°ΡΠΈΠ½Π½ΠΎ-Π·Π°Π²ΠΈΡΠΈΠΌΡΠ΅ ΠΎΠΏΡΠΈΠΈ(ΠΎΠΏΡΠΈΠΈ ΠΊΠΎΠΌΠΏΠΈΠ»ΡΡΠΎΡΠ°) #define CONSTANT(paaram1) definition //ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΠΌ ΠΌΠ°ΠΊΡΠΎΡ #ifdef CONSTANT //Π²ΠΊΠ»ΡΡΠ°Π΅Ρ Π΄Π°Π»ΡΠ½Π΅ΠΉΡΠΈΠΉ ΠΊΠΎΠ΄, Π΅ΡΠ»ΠΈ ΠΊΠΎΠ½ΡΡΠ°Π½ΡΠ° ΠΠΠ ΠΠΠΠΠΠΠ #ifndef CONSTANT //Π²ΠΊΠ»ΡΡΠ°Π΅Ρ Π΄Π°Π»ΡΠ½Π΅ΠΉΡΠΈΠΉ ΠΊΠΎΡ ΡΠΎΠ»ΡΠΊΠΎ Π΅ΡΠ»ΠΈ ΠΊΠΎΠ½ΡΡΠ°Π½ΡΠ° ΠΠ ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½Π° #else //ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠ΅ΡΡΡ Ρ Π΄Π²ΡΠΌΡ ΠΏΡΠ΅Π΄ΡΠ΄ΡΡΠΈΠΌΠΈ. ΠΠΊΠ»ΡΡΠ°Π΅Ρ ΠΈΠ»ΠΈ ΠΈΡΠΊΠ»ΡΡΠ°Π΅Ρ Π΄Π°Π»ΡΠ½Π΅ΠΉΡΠΈΠΉ //ΠΊΠΎΠ΄ Π² Π·Π°Π²ΠΈΡΠΈΠΌΠΎΡΡΠΈ ΠΎΡ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ ΡΡΠ»ΠΎΠ²ΠΈΡ ΠΏΡΠ΅Π΄. ΡΠ°Π·Π΄Π΅Π»Π° #endif //ΠΊΠΎΠ½Π΅Ρ ΡΡΠ»ΠΎΠ²Π½ΠΎ Π²ΠΊΠ»ΡΡΠ°Π΅ΠΌΡΡ
/ΠΈΡΠΊΠ»ΡΡΠ°Π΅ΠΌΡΡ
ΡΡΠ°Π³ΠΌΠ΅Π½ΡΠΎΠ² ΠΊΠΎΠ΄Π°
Like that...
UPD: The ## operator is used very infrequently, so you donβt have to think about it ...
- It is used infrequently because they do not think about it. And we are talking about operators and not about directives. - Alexey Kotov
- We are talking about their use! Can anyone describe the operator without giving examples of use? Some kind of nonsense ... UPD: not just to describe, but understandably describe! - 3JIoi_Hy6