`volatile' on local variable used outside of function

N

nickptar

Let's say I have a situation like this:

/* begin example.c */
static int* ptr;

static void inner_fn(void)
{
*ptr = 1;
}

void outer_fn(void)
{
int i = 0;
ptr = &i;
inner_fn();
printf("%d\n", i);
}
/* end example.c */

in which a global pointer is set to point to a function-local variable
and then written to in another function. Do I then have to declare `i'
as `volatile' to get the expected behavior?
 
W

Walter Roberson

Let's say I have a situation like this:
/* begin example.c */
static int* ptr;
static void inner_fn(void)
{
*ptr = 1;
}
void outer_fn(void)
{
int i = 0;
ptr = &i;
inner_fn();
printf("%d\n", i);
}
/* end example.c */
in which a global pointer is set to point to a function-local variable
and then written to in another function. Do I then have to declare `i'
as `volatile' to get the expected behavior?

No.

Effectively, you only need volatile for variables that might
be changed by something outside the normal flow of control,
such as by a signal handler.

You do, though, need to #include <stdio.h> to get the expected behaviour.
And you will need a main() somewhere along the line.
 
G

Guillaume

nickptar said:
/* begin example.c */
static int* ptr;

static void inner_fn(void)
{
*ptr = 1;
}

void outer_fn(void)
{
int i = 0;
ptr = &i;
inner_fn();
printf("%d\n", i);
}
/* end example.c */

Do I then have to declare `i'
as `volatile' to get the expected behavior?

Any decent compiler should detect that you're using a pointer to this
local variable. I don't think you need to declare it "volatile".

If I'm wrong, I'd like to see a reasonable explanation.
 
C

Christian Bau

"nickptar said:
Let's say I have a situation like this:

/* begin example.c */
static int* ptr;

static void inner_fn(void)
{
*ptr = 1;
}

void outer_fn(void)
{
int i = 0;
ptr = &i;
inner_fn();
printf("%d\n", i);
}
/* end example.c */

in which a global pointer is set to point to a function-local variable
and then written to in another function. Do I then have to declare `i'
as `volatile' to get the expected behavior?

If the "expected behavior" is that calling inner_fn() sets i to 1, then
there is absolutely no need to declare i as volatile. "volatile" is used
for objects that could be modified by things outside your C code.

Actually, declaring i as volatile int would be a huge mistake: If an
object is volatile, then it is illegal to modify it through a
non-volatile pointer, and it invokes undefined behavior. You would have
to change the declaration of ptr to:

static volatile int* ptr;
 

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

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top