How memory is allocated to macros in c?

2020-04-16 04:01发布

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?

4条回答
姐就是有狂的资本
2楼-- · 2020-04-16 04:40

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.

查看更多
混吃等死
3楼-- · 2020-04-16 04:44

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.

查看更多
够拽才男人
4楼-- · 2020-04-16 04:54

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.

查看更多
Animai°情兽
5楼-- · 2020-04-16 04:55

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.

查看更多
登录 后发表回答