A.1.2 Defining variables for use during both ordinary and interrupt processing
Specify volatile qualifier to the variables that are to be used during both ordinary and interrupt processing.
When a variable is defined with the volatile qualifier, the variable is not optimized. The reference to the volatile variables is compiled to the code which always read the value from memory, and the assignment to the volatile variables is compiled to the code which always write the value to memory. The access order, access width, and access count of volatile variables are not changed. A variable for which volatile is not specified may be assigned to a register as a result of optimization and the code that loads the variable from the memory may be deleted. When the same value is assigned twice to a variable for which volatile is not specified, the latter assignment instruction may be deleted as a result of optimization because it is interpreted as a redundant instruction.
Example 1. | Example of source and output code image when volatile is not specified
If variables a and b are not specified with the volatile quantifier, they may be assigned to registers, and may be optimized. |
int a;
int b;
void func(void){
if(a <= 0){
b++;
} else {
b+=2;
}
b++;
}
|
_func:
movw ax, !LOWW(_a)
xor a, #0x80
cmpw ax, #0x8001
movw ax, !LOWW(_b)
bnc $.BB@LABEL@1_3
.BB@LABEL@1_1: ; bb1
incw ax
.BB@LABEL@1_2: ; bb9
incw ax
movw !LOWW(_b), ax
ret
.BB@LABEL@1_3: ; bb3
incw ax
br $.BB@LABEL@1_1
|
Example 2. | Source and output code when volatile has been specified
If the volatile qualifier is specified for variables a and b, the output code is such that the values of these variables are always read from and written to memory when values are assigned to them.
When volatile is specified, the code size increases compared with when volatile is not specified because the memory has to be read and written. |
volatile int a;
volatile int b;
void func(void){
if(a <= 0){
b++;
} else {
b+=2;
}
b++;
}
|
_func:
movw ax, !LOWW(_a)
xor a, #0x80
cmpw ax, #0x8001
bnc $.BB@LABEL@1_2
.BB@LABEL@1_1: ; bb1
onew ax
br $.BB@LABEL@1_3
.BB@LABEL@1_2: ; bb3
movw ax, #0x0002
.BB@LABEL@1_3: ; bb3
addw ax, !LOWW(_b)
.BB@LABEL@1_4: ; bb9
movw !LOWW(_b), ax
incw !LOWW(_b)
ret
|