Home > Backend Development > C++ > body text

The difference between macros and functions in C

王林
Release: 2023-08-30 23:49:06
forward
1045 people have browsed it

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.

Example

#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));
}
Copy after login

Output

Use of sqr(). The value of sqr(3+2): 25
Use of SQUARE(). The value of SQUARE(3+2): 11
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template