#define macro definition

Small example of #define macro definition

#include <stdio.h>
#include <iostream>

#define SUB(x,y) x - y
#define ACCESS_BEFORE(element, offset, value) *SUB(&element, offset) = value

using namespace std;

int main() {
    int i;
    int array[10] = {1,2,3,4,5,6,7,8,9,10};
    ACCESS_BEFORE(array[5], 4, 6);
    for(i = 0; i < 10; i++) {
        cout<<array[i]<<endl;
    }
    return 0;
} 

The macro definition is replaced with: *&array[5] - 4 = 6
&array[5] means the address of array[5]
*&array[5] means that array[5]
is equivalent to array[5] - 4 = 6, since the left side is an expression. In an assignment expression, the lvalue must be a modifiable memory block, and the lvalue of the above expression is a literal constant, which cannot be compiled, so the compilation will report an error.

C language compilation is divided into pre-compilation, compilation, linking, and finally an executable file is formed. Macro replacement is performed in the pre-compilation phase, and no syntax check is performed, but the legality of each expression is checked in the compilation phase.

If you want the program to run correctly, you need to change the macro definition part to:

#define SUB(x,y) (x - y)
#define ACCESS_BEFORE(element, offset, value)*SUB(&element, offset) = value

The macro definition part is equivalent to being replaced by: *(&array[5] - 4) = 6
The address of array[5] is moved forward by 4 bits, that is, array[1] = 6,
so the result of the program running is: 1 6 3 4 5 6 7 8 9 10

#define defines the min function

#define MIN(A, B) ((A) <= (B) ? (A) : (B))

Notes:
1. The function defined by #define will be directly embedded in the code
2. Triple conditional operator? : instead of if
3. In macro definitions, carefully surround parameters with parentheses
4. Do not end with a semicolon

Reprint link: https://blog.csdn.net/u010429424/article/details/74147588?locationNum=1&fps=1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324729599&siteId=291194637