Home >Backend Development >C++ >The difference between macros and functions in C
In this section, we will see the difference between macros and functions in C language. Macros are preprocessed, which means that all macros are preprocessed at compile time. Functions are not preprocessed, but compiled.
Type checking is not performed in macros, so problems with input of different types may occur. With functions, this doesn't happen. Additionally, if the macro's input is not maintained correctly, some invalid results may be produced. Please review the following procedure for questions.
#include <stdio.h> #define SQUARE(x) x * x int sqr(int x) { return x*x; } main() { printf("Use of sqr(). The value of sqr(3+2): %d</p><p>", sqr(3+2)); printf("Use of SQUARE(). The value of SQUARE(3+2): %d", SQUARE(3+2)); }
Use of sqr(). The value of sqr(3+2): 25 Use of SQUARE(). The value of SQUARE(3+2): 11
Function and macro, we want both to perform the same task, but here we can see that the output results are different. The main reason is that when we pass 3 2 as function parameter, it is converted to 5 and then calculates 5 * 5 = 25. For the macro, it executes 3 2 * 3 2 = 3 6 2 = 11.
Therefore, macros are not recommended for the following problems:
No type checking
Defaults to debug mode because macros Just simply replace the
macro with no namespace. So if a macro is defined in one section, it can be used in another section.
The macro increases the code length because it is added before preprocessing.
The macro does not check for any compile-time errors.
The above is the detailed content of The difference between macros and functions in C. For more information, please follow other related articles on the PHP Chinese website!