N
Noob
Hello,
I'm trying to understand volatile. I have written trivial code
where a variable is tested to decide whether to break early out
of a loop.
I've considered 4 different cases.
auto variable
static with function scope
static with file scope
external linkage
AFAIU, since the abstract machine model is single threaded,
if a variable is not volatile, then its value cannot change
inside the loop. (Signals might be an exception?)
Thus, in every case, the compiler is allowed to remove the
test, because it may assume that the variable cannot change.
I tested with gcc -O3
In autovar, staticfuncvar, and filescopevar gcc removed the test.
In globalvar, gcc did not remove the test.
Is it unsafe for the compiler to assume that global's value
cannot change between two iterations of the loop?
(Signals might play a role here. A different "module" might
catch a signal, and change the value of the variable inside
the signal handler?)
If so, does that mean that volatile is not needed in the case
of a variable with external linkage?
Regards.
void foo(void);
void autovar(void)
{
int i;
int local = 0;
for (i = 0; i < 1000; ++i)
{
if (local) break;
foo();
}
}
void staticfuncvar(void)
{
int i;
static int local = 0;
for (i = 0; i < 1000; ++i)
{
if (local) break;
foo();
}
}
static int flocal = 0;
void filescopevar(void)
{
int i;
for (i = 0; i < 1000; ++i)
{
if (flocal) break;
foo();
}
}
int global = 0;
void globalvar(void)
{
int i;
for (i = 0; i < 1000; ++i)
{
if (global) break;
foo();
}
}
I'm trying to understand volatile. I have written trivial code
where a variable is tested to decide whether to break early out
of a loop.
I've considered 4 different cases.
auto variable
static with function scope
static with file scope
external linkage
AFAIU, since the abstract machine model is single threaded,
if a variable is not volatile, then its value cannot change
inside the loop. (Signals might be an exception?)
Thus, in every case, the compiler is allowed to remove the
test, because it may assume that the variable cannot change.
I tested with gcc -O3
In autovar, staticfuncvar, and filescopevar gcc removed the test.
In globalvar, gcc did not remove the test.
Is it unsafe for the compiler to assume that global's value
cannot change between two iterations of the loop?
(Signals might play a role here. A different "module" might
catch a signal, and change the value of the variable inside
the signal handler?)
If so, does that mean that volatile is not needed in the case
of a variable with external linkage?
Regards.
void foo(void);
void autovar(void)
{
int i;
int local = 0;
for (i = 0; i < 1000; ++i)
{
if (local) break;
foo();
}
}
void staticfuncvar(void)
{
int i;
static int local = 0;
for (i = 0; i < 1000; ++i)
{
if (local) break;
foo();
}
}
static int flocal = 0;
void filescopevar(void)
{
int i;
for (i = 0; i < 1000; ++i)
{
if (flocal) break;
foo();
}
}
int global = 0;
void globalvar(void)
{
int i;
for (i = 0; i < 1000; ++i)
{
if (global) break;
foo();
}
}