You get a bonus - 1 coin for daily activity. Now you have 1 coin

8.6. Directives preprocessor.

Lecture



  8.6.  Directives preprocessor.

  8.6.  Directives preprocessor.

One of the most common directives is the #define directive. This directive is used to define the purpose of the identifiers specified in it. Using this directive looks similar to working with constants. Each #define line consists of three parts:
1) the directive itself;
2) your chosen abbreviation or identifier, which is called the macro;
3) substituted values ​​or replacement list or body.
A process that begins with a macro and ends with a replacement process is called a macro expansion .  8.6.  Directives preprocessor.


Example:
#include
#define TWO 2
#define FOUR TWO * TWO
#define PX printf ("x is% d, \ n", x)
int main (void)
{
int x = TWO;
PX;
x = FOUR;
PX;
}
When executing the above program at the preprocessing stage, the following replacements occur: the string int x = TWO is replaced by int x = 2; PX string on printf (...); x = FOUR on x = TWO * TWO, and then on x = 2 * 2. This is where the macro expansion process ends, i.e. at the preprocess stage, multiplication is not executed, and only the proposed substitutions are executed.
The result of the program will be the output of two lines:
x is 2
x is 4
When declaring values ​​exceeding the length of a string by the #define directive, it is possible to split the value into several lines using the " \ " symbol.
Example:
#include
#define PX printf ("Today is the first pa \
Swarm - Algorithmization. \ n ")
int main (void)
{
PX
}
If in the above example, before the syllable "swarm" put a few spaces, they will be displayed in the resulting line. Using the arguments of the #define directive, you can create function macros that look and act like functions.
Example:
#define SQUARE (x) x * x
This directive can be used in the following statements:
int x = 4;
int z;
1) z = SQUARE (2);
2) z = SQUARE (x);
3) z = SQUARE (x + 2);
4) z = 100 / SQUARE (2);
At the preprocess stage, the first record will be replaced by z = 2 * 2; the second at z = x * x; the third is at z = x + 2 * x + 2; fourth on 100/2 * 2. Accordingly, the results will be: 4, 16, 14, 100.
If in the third case it is necessary to execute the action (x + 2) * (x + 2), then the inline value in the #define directive must be replaced by (x) * (x). In this case, in the fourth record, we get z = 100 / (2) * (2). To execute this action as 100 / (2 * 2), you need to write ((x) * (x)) in the #define directive.
Sometimes even the prescribed precautions will not allow for the desired result. For example, if increment or decrement is used as an argument.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Algorithmization and programming. Structural programming. C language

Terms: Algorithmization and programming. Structural programming. C language