简体   繁体   中英

Is it possible to get the address of a macro?

#define N 100

&N not possible. How can I know the address of N? It must have some address.

A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro.

So NO N is not a variable and you can't get the address of N

MACROS

宏没有任何地址,这就是为什么它们被称为常量值。

A macro is simple text substitution. If you write code like

int* ptr = &N;

it will then be pre-processed into

int* ptr = &100;

100 is an integer literal and all integer literals are constant rvalues, meaning you can't assign a value to it, nor can you take its address.

The literal 100 is of course stored in memory though - you can't allocate numbers in thin air - but it will most likely be stored as part of the executed program code. In the binary, you'll have some machine code instruction looking like "store 100 in the memory location of the pointer variable" and the 100 is stored in that very machine code instruction. And a part of a machine code instruction isn't addressable.

It is simple text substitution. The compiler's pre-processor replaces all occurrences of N with 100 , but, it depends on what N is. In your example taking the address of a constant won't compile, but these two other examples do work.

#include <stdio.h>

#define N 100
#define M x
#define L "Hallo world!"

int main()
{
    int x = 42;
    //printf ("Address of 'N' is %p\n", (void*)&N);  // error C2101: '&' on constant
    printf ("Address of 'M' is %p\n", (void*)&M);
    printf ("Address of 'L' is %p\n", (void*)&L);
    return 0;
}

Program output:

Address of 'M' is 0018FF3C
Address of 'L' is 0040C018

MORE explanation.

With #define N 100 you can't get the address of N because a numerical constant like that does not have a single memory location. 100 might be assigned to the value of a variable, or indeed the optimising compiler might load 100 directly into a processor register.

In the case of #define M x that's a simple substitution so that M can be used exactly as x can. There is no functional difference between &x and &M because the two statements are identical after the preprocessor has made the substitution.

In the case of #define L "Hallo world!" we have a string literal, which the compiler does place in memory. Asking for &L is the same as asking for &"Hallo world!" and that is what you get.

N is not a variable, it never has any address. It's just a value to get pasted in when you use patterns like int val=N; . Then you can get the address of val using & .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM