Categories
Mastering Development

withoutwith volatile global variable in for loop

I’m new to C, just a question on volatile variables. We know that using volatile,we force the compiler to issue instructions that read variables from main memory instead of reading from cache/registers, below is the c code

volatile int count = 0;
void foo(int count) {
   int i;
   for (i = 0; i < count; i++) {
      count ++;
   }
}

int main()
{
   foo(3);
}

And below is the assembly code

foo:
.LFB39:
    .cfi_startproc
    endbr64
    movl    $0, %eax
.L2:
    cmpl    %edi, %eax
    jge .L4
    addl    $1, count(%rip)
    addl    $1, %eax
    jmp .L2
.L4:
    ret
    .cfi_endproc

But if I don’t use volatile for the count variable, the assembly code is

foo:
.LFB39:
    .cfi_startproc
    endbr64
    movl    $0, %eax
.L2:
    cmpl    %edi, %eax
    jge .L4
    addl    $1, count(%rip)
    addl    $1, %eax
    jmp .L2
.L4:

And We can see that addl $1, count(%rip) is still reading the variable from the main memory, no cache, registers involved,so nothing special about volatile?

Leave a Reply

Your email address will not be published. Required fields are marked *