gpt4 book ai didi

c - C 中堆栈上的变量创建

转载 作者:行者123 更新时间:2023-12-02 20:12:44 24 4
gpt4 key购买 nike

我想知道是否在堆栈上创建了变量。考虑以下三个带有变量 b 的函数 f、g 和 h:

void f(int a) {
int b;
if (a == 0) {
return;
}
// do sth with b;
return;
}

void g(int a) {
if (a == 0) {
return;
}
int b;
// do sth with b;
return;
}

void h(int a) {
if (a == 0) {
return;
} else {
int b;
// do sth with b;
return;
}
}
  1. 什么情况下会在堆栈上创建 b?
  2. 编译器优化级别如何影响此行为?
  3. 是否有一种更好的选择?

最佳答案

In which cases will b be created on the stack?

通常三个都是,因为b是一个自动变量。在某些情况下,编译器可能 store b in a CPU register ,但你不能强制它发生,这是编译器的选择。

How does the compiler optimization level affect this behavior?

依赖于编译器。

由于您假设您使用 b 做了一些(有用的)事情,因此它可能不会被优化。如果确实如此,这取决于编译器以及您对 b 执行的实际工作是什么,则 b 根本不会在堆栈中创建。

Is there one option which is preferable?

在需要的 block 的顶部尽可能接近其用法创建变量b

我会选择g(),因为它是最简洁的函数(与其他函数相比,它使用最少数量的字符来实现相同的目的)。此外,它会在使用之前创建 b

PS:当然g()只能使用一个返回,但你明白了。

关于c - C 中堆栈上的变量创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53204569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com