pragma push/pop_macro指令的栈是否为每个宏独有?附示例求证
Great question! The short answer is: each macro has its own independent stack for push_macro/pop_macro operations—they don’t share a single global stack.
Let’s break down the provided example code to prove this point clearly:
First, here’s the code for reference:
// pragma_directives_pop_macro.cpp // compile with: /W1 #include <stdio.h> #define X 1 #define Y 2 int main() { printf("%d",X); printf(" %d",Y); #define Y 3 // C4005 #pragma push_macro("Y") #pragma push_macro("X") printf(" %d",X); #define X 2 // C4005 printf(" %d",X); #pragma pop_macro("X") printf(" %d",X); #pragma pop_macro("Y") printf(" %d",Y); }
The output is: 1 2 1 2 1 3
Let’s walk through the key steps that confirm per-macro stacks:
- We start with
X=1andY=2, which gives the first two output values. - We redefine
Yto 3, then push this new value ofYonto its dedicated stack. - Next, we push the original value of
X(1) onto its separate stack. - We redefine
Xto 2 and print it—this only affects the current active value ofX, not the stack associated withY. - When we pop
X, it reverts to the pushed value (1), with zero impact onY’s stored state. - Finally, popping
Yreverts it to the value we pushed (3), which doesn’t interfere withX’s current value at all.
If there was a single shared stack, we’d see cross-contamination between macro states, but the clean separation of X and Y throughout the execution confirms each macro manages its own stack of previous definitions.
内容的提问来源于stack exchange,提问作者Hrothgar
相关产品推荐
相关产品推荐

