Deeply understand the definition of C language-Alibaba Cloud Developer Community

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;

for example:

#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:

int a[MAX_SIZE];

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:

UST a;

function 4: it can actually be used in other languages.

For example: Chinese programming language, easy language

for example, use Chinese programming:

execution effect:

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...

This is one of the reasons why C language can be used as other programming languages. For example, writing PHP interpreter in C language can create PHP programming language...

Selected, One-Stop Store for Enterprise Applications
Support various scenarios to meet companies' needs at different stages of development

Start Building Today with a Free Trial to 50+ Products

Learn and experience the power of Alibaba Cloud.

Sign Up Now