static question

C

copx

I know that a variable declared static at the beginning of a function will
stick around until the program terminates, e.g.:

void func(void)
{
static foo;
..
}

But does the same apply to variables which are declared static inside a
sub-function block, e.g.

void func(void)
{
while (..) {
static foo;
}
}

I think 'foo' only lasts while the loop is executed, but I am not sure.
I mean, it would be kind of confusing if it were that way..
 
B

Ben Bacarisse

copx said:
I know that a variable declared static at the beginning of a function will
stick around until the program terminates, e.g.:

void func(void)
{
static foo;
..
}

But does the same apply to variables which are declared static inside a
sub-function block, e.g.
Yes.

void func(void)
{
while (..) {
static foo;
}
}

I think 'foo' only lasts while the loop is executed, but I am not
sure.

The name is only visible inside the block, but the variable exists
for the whole execution of the program.
I mean, it would be kind of confusing if it were that way..

It would. If your second 'foo' came and went as execution enters
leaves the block, it would be an automatic variable -- i.e. just like
a normal one declared without 'static'.

You are using implicit int. 'static int foo;' is better.
 
C

Citizen C

I know that a variable declared static at the beginning of a function
will stick around until the program terminates, e.g.:

void func(void)
{
static foo;
..
}

But does the same apply to variables which are declared static inside a
sub-function block, e.g.

void func(void)
{
while (..) {
static foo;
}
}

Yes, the same applies.

It should be noted that you specify no explicit type for foo. It is
better to write this:

static int foo;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top