What are Macros and how to use them?

Asked

Viewed 2,796 times

7

So far during my C programming course, the only contact I had with macros came from standard libraries and not really knowing what was going on when calling these macros. I would like to know exactly what macros are, how to create a C/C++ and the difference between macro, function and constant. Thank you.

1 answer

5


Macros or Microinstructions is a pre-compilation (preprocessing) feature that allows you to create structures that will be replaced before code is compiled.

A macro can represent a simple string that will repeat in quantity in the code, as well as a relatively complex code block or within an application domain, but repeated several times in the code, and the function call would be inelegant.

In the case of code macros, they can be used to create dialects of the language with C or C++ for a specific domain, so one can adopt names of mathematical constants, named code blocks that are better organized and readable to domain experts in use.

Macros can also be used to identify constants that will be used to define architectures, restructuring the code by creating a conditional build.

Code files are interpreted by pre-compiler who replaces such macros with their representations, generating a new code file that will be compiled.

When a Macro calls other macros it is important to take certain precautions as suggested in the article C-Preprocessor Tricks, Tips and Idioms.

Other information on Preprocessing in C (in English)

  • 1

    I think it’s worth mentioning that the use of macros in C++ is usually not well seen because macros do not offer type security, do not respect scope (I’m looking at you min and max from windows.h rs) and may make it difficult to understand how a piece of code works when they do something that could not be done with other language features. Citing his answer, in C++ it is generally preferable to use constant variables for mathematical constants and functions (possibly templates) for named code blocks, thus avoiding the mentioned problems.

  • 1

    Exact @Tiagogomes, thanks for complimenting, including the last link I sent talks about it at the end, but it’s in English.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.