In the previous article, we talked about the pre-compiled instruction# include. There is also a common pre-compiled instruction:#define. Its surface meaning is definition, which is usually called "definition constant", but its real function is replacement;
#define SUCCESS 1
the whole sentence defines a macro replacement, in which the SUCCESS is the macro name, followed by the value;
in the following program, directly use SUCCESS to represent 1. However, SUCCESS is not a variable. Although it looks like a constant, its value does not change. However, the real constant follows the compiler, that is, you can print a constant in later debugging, for example, const a = 3; you can print out the value of a. However, the# define item is replaced during pre-compilation, that is, you cannot see the SUCCESS during compilation, and it is directly replaced with 1, this is also one of the differences from const. This is the use of a macro and the replacement of a macro.
Let's see what# define does?
Function 1: it is convenient for programmers to detect.
Because in many cases, for example, you may use 1. If you write 1 directly, 1 May appear in many places. Later, you see 1, it is difficult to know what the meaning of 1 here is immediately. We should consider it in combination with the context, which makes ourselves troublesome. In this case, you can use these macros to express it, so that it can be "clear at a glance". If you write SUCCESS, you can know the meaning of successful operation at once.
Function 2: convenient maintenance.
For example, can be used to define array capacity
#define MAX_SIZE 100
you can use this method later:
in the future, if the capacity is less, you can directly modify the macro, and the usage will be the latest, because you will recompile...
Function 3: simplify writing
for example, it can be defined as follows:
#define unsigned short UST
the following code can be written:
function 4: it can actually be used in other languages.
For example: Chinese programming language, easy language
for example, use Chinese programming:
the reason is that it is written in the header file as follows:
because according to the previous section, we know that h can be defined casually...