Macro definitionis a commonly used preprocessing directive, which uses "identifier" to represent the content in the "replacement list". The identifier is called a macro name. During the preprocessing process, the preprocessor will replace all macro names in the source program with the contents in the replacement list in the macro definition.
There are two common macro definitions, macro definitions without parameters and macro definitions with parameters.
Macro definitions can help us prevent errors and improve code portability and readability.
In the process of software development, there are often some commonly used or common functions or code segments. These functions can be written as functions or encapsulated into macro definitions. So is it better to use functions or macro definitions? This requires us to make a reasonable choice between the two.
Let’s look at an example to compare the size of two numbers or expressions. First we write it as a macro definition:
#define MAX( a, b) ( (a) > (b) (a) : (b) ) # 其次,把它用函数来实现: int max( int a, int b) { return (a > b a : b) }
Obviously, we will not choose to use a function to complete this task. There are two reasons: First, function calling will bring additional overhead. It needs to open up a stack space, record the return address, push the formal parameters onto the stack, and release the stack when returning from the function. This overhead will not only reduce code efficiency, but also greatly increase the amount of code. The use of macro definitions is superior to functions in terms of code size and speed; secondly, the parameters of the function must be declared as a specific type. So it can only be used on expressions of the appropriate type. If we want to compare the sizes of two floating point types, we have to write a comparison function specifically for floating point types. On the contrary, the above macro definition can be used for integers, long integers, single floating point types, double floating point types, and any other types that can use the ">" operator to compare the size of values. In other words, the macro is independent of the type. of.
Compared with using functions, the disadvantage of using macros is that every time a macro is used, a copy of the macro definition code will be inserted into the program. Unless the macro is very short, using macros can significantly increase the length of your program.
The above is the detailed content of How to define macro definition in C language. For more information, please follow other related articles on the PHP Chinese website!