Magic volatile word

Hello Friends.
Please help me out.

How I think , that word volatile have a sense when compiler’s optimize option is turn on.

I have a struct:

typedef struct ParQueue
bool enq;
bool ask;

When I change struct like this

typedef struct ParQueue
volatile bool enq;
volatile bool ask;

Then size of result exe file is changed (build variant - release). This is my compiler args qcc -V4.2.4,gcc_ntox86 -c -Wc,-Wall -Wc,-Wno-parentheses -O -w9 -O0 -fno-inline-functions -DNDEBUG -DBUILDENV_qss. As you see I specially turn off optimizer. (In Momentics → Project Properties → Compiler → No optimize).

Please help me out Why result size of executable was changed???

Volatile is an important message to the compiler which concerns optimization. Here’s a simple example.

int i;
void routine()
i = 0;
if (i > 1000000)

As it stands, the compiler could create code like this.

load ax-register with 0
increment ax-register
if (ax-register > 1000000
store ax-register to i;
jump to loop

However if you add volatile to the int i, this code is no longer valid.
Instead, either the memory location of i must be incremented or after each increment of the ax-register it would need to be stored. That’s because another thread or context (eg. interrupt handler) could change the value of i.

Writing an optimizing compiler is a tricky endeavor. A simplification could be eliminating certain optimizations just because “volatile” appears in the code. This would not be optimal, but it would work.

Hello Maschoen.

You want to say, that even I turn off optimize feature of compiler (via -O0 gcc’s option ), all the same volatile variables is processing by compiler

Why when I add volatile word to the declaration of variable, result size of binary was changed???/

If you use “volatile” it may turn off optimizations that you request.

If you use “volatile” it may turn off optimizations that you didn’t request.

Either way it can change the size of your code, which is what you are seeing.

If you want to understand this more, I suggest that you have the compiler show you
the assembler source it is creating with and without “volatile”.

Using registers of the CPU isn’t an optimization. So, if you turn off optimization, still the compiler will make use of CPU registers - that’s what they are for. Only when you specify volatile, CPU registers will not be used for the volatile var. So different code will be generated and that explains why the executable length is different.

Ok , thanks for explaination