Reputation: 61
I am wondering if a variable is created on the stack or not. Consider the following three functions f,g and h with the variable b:
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;
}
}
Upvotes: 2
Views: 2388
Reputation: 213960
In which cases will b be created on the stack?
How does the compiler optimization level affect this behavior?
Impossible to tell without a specific system in mind. It depends on the calling convention and how the compiler optimizes the code. It may be allocated on the stack or inside a register.
That being said, your 3 cases are mostly about coding style. If b
is needed and is allocated on the stack, that memory will probably get allocated early on no matter where the variable is placed. Or similarly, if the compiler is able to optimize memory use based on if the variable is used or not, the compiler will then allocate the memory just before the variable is used, regardless of where the variable declaration is located in the C source code.
Is there one option which is preferable?
Generally, keep the variable declaration close to where it is used. If you can narrow the scope, it's always a good thing. But that's for the sake of reducing scope, avoiding namespace collisions, private encapsulation etc. Not for the sake of performance.
Upvotes: 2
Reputation: 91
Every function has your own frame(place where will be storing all local variables, parameters, etc.). All local variables is an automatic variables because they will be destroy after return
operator. All variables which was created without (malloc
, calloc
, realloc
, etc) will be stored on the stack. So, yes all variables in your code will be stored on the stack.
Upvotes: -2
Reputation: 73376
In which cases will b be created on the stack?
Usually all three, since b
is an automatic variable. In some cases, the compiler may store b
in a CPU register, but you cannot force it to happen, it's the compiler's choice.
How does the compiler optimization level affect this behavior?
Compiler dependent.
Since you assume that you do something (useful) with b
, it will be probably not optimized out. If it does, which depends on the compiler and what is the actual work that you do with b
, then b
won't be created at all in the stack.
Is there one option which is preferable?
Create variable b
as close as possible to its usage, at the top of the block where it is needed.
I would go for g()
, since it's the most laconic function (it uses the minimum amount of characters in contrast with the others, to achieve the same purpose). Moreover, it creates b
just before its usage.
PS: Of course g()
could use only one return
, but you get the idea.
Upvotes: 5