在 GCC C 中,有没有办法将数据推送/弹出到 C 返回堆栈?
我不是在谈论实现我自己的堆栈(我知道该怎么做);我的意思是使用现有的 C 返回堆栈来显式压入/弹出参数(当然是在同一级别的大括号内)。
例如,像这样的东西:
extern int bar;
void foo(void) {
PUSH(bar);
bar = 12;
doSomething(); // that depends on the value of bar
bar = POP(); // restore original value of bar
}
如果有任何简单的方法可以做到这一点,我认为这将是一种比显式使用局部变量(如“oldBar”)更简洁的替代方法。
最佳答案
如果使用临时变量,基本上是一样的。临时变量分配在堆栈上或优化到寄存器。
例如
extern int bar;
void foo(void) {
int tmp = bar
bar = 12;
doSomething(); // that depends on the value of bar
bar = tmp; // restore original value of bar
}
显然,C 实际上并不需要用于调用的堆栈结构,因此此功能没有意义。这是本文内存布局部分声明的https://www.seebs.net/c/c_tcn4e.html
Quite simply, not every compiler even has a "stack". Some systems don't really have any such feature. Every compiler for C has some kind of mechanism for handling function calls, but that doesn't mean it's a stack. More significantly, it is quite common for function parameters or local variables not to be stored on any "stack", but to be stored in CPU registers. That distinction can matter a lot, and should have been covered, rather than hand-waved away.
从技术上讲,您也可以使用 alloca()(位于 alloca.h 中)来执行此操作,但释放该内存的唯一方法是让函数调用返回。它也没有真正按照你的建议去做。 alloca 也不是 C 标准的一部分
关于我可以将数据推送/弹出到 GCC C 返回堆栈吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701141/