Reputation: 2894
Consider the following C function.
Does opening the braces to create a local scope make compilers create a record on the stack to mantain the variables declared in the scope ?
void function()
{
int q,r;
...
{
int i = 0;
int j = 3;
q = j + 1;
}
...
}
If so , do compilers act the same with while blocks?
example:
void function()
{
int q,r;
...
while(conditions)
{
int i = 0;
int j = 3;
q = j + 1;
}
...
}
Upvotes: 2
Views: 142
Reputation: 123448
Based on behavior I've seen in the past, I'd say "probably not". IME, only a single stack frame gets created for all the function's variables, regardless of how they're scoped within the function.
Restricted scoping is something the compiler enforces at translation time; there's no real need to do it at run time.
Upvotes: 0
Reputation: 145829
{}
is called the compound statement (also called block ) and it introduces a new block scope. It means here:
void function(void)
{
int q,r;
...
{
int i = 0;
int j = 3;
q = j + 1;
}
...
}
q
and r
are destroyed at the end of the function; i
and j
are destroyed at the end of the local block scope. The lifetime of an automatic object is limited to the block where it is declared.
For iteration statement like the while
statement, this is exactly the same, the while
statement is defined as:
while (expression) statement
If you use a compound statement (a block) for the statement in while
it will also introduce a new scope.
Now on the stack level, C does no require a stack so it implementation details.
Upvotes: 1
Reputation: 816
It depends on compiler. Good modern compiler would optimize this code. It would count
int j = 3;
q=j+1;
at compilation time and make something like
q=4;
The same for the second example. The variable j would be put on stack or maybe even in a register, its value set as 3 and then would be processed through cycle iterations.
Upvotes: 1
Reputation: 272467
The arrangement of the stack is not specified by the C standard.
Curly braces ({}
) introduce a new scope, so in principle, yes, this could create a new frame on the stack. But the compiler may choose to optimise this overhead away.
Upvotes: 4