How memory is allocated to macros in c?

2020-04-16 04:42发布

问题:

I would like to know how the memory is allocated to #define variables in C.

#define VAR1 10

I have 2 questions...

  1. What's the type of VAR1?
  2. In which memory segment VAR1 is stored?

回答1:

VAR1 has neither a type nor any runtime representation. It's only recognized by the preprocessor.

So the answer is Mu: your question cannot be answered because it is based on incorrect assumptions.



回答2:

In which memory segment VAR1 is stored?

In none of the segment.

VAR1 is relevant only in pre-processing stage and does not have any identity at run time. During pre-processing all instances of VAR1 are replaced with 10 so there is no memory requirement at run time because 10 is an integer literal.

What's the type of VAR1?

VAR1 is replaced with 10 at pre-processing stage. 10 being an integer literal, we can say type or VAR1 is int.


Moral: Macros are not variables.



回答3:

To my understanding, a definition via a macro does neither have a type nor explicitly allocates memory; the right-hand side of the definition (10 in this case) is expanded textually into any occurence of the left-hand side (VAR1 in this case) before the compilation.



回答4:

Macros are not variables. They are just a common name for some value. In your case, VAR1 corresponds to integer value 10.

Macro is not stored anywhere in the memory. When we compile the program in C or C++, it is done in many stages. First, the syntax is checked. If syntax is correct, it is checked for semantic errors. If it passes then, the .c program file is converted into Object code. During this conversion, the preprocessors are processed i.e. the header files are included, any external linked file is included and all the macro are replaced with their corresponding values (in your case, at any place the program finds VAR1, it will replace that with value 10).

After this phase, all the code has already been converted to nearly machine level code.

I hope you got your answer.