Search code examples
cgccoptimization

Compiler optimizations in gcc


I have a code in C and I am running some tests. I need to access an array, but in "read-only" mode. I am doing something like this:

for (int i= 0; i < 1000; i++){
    int a = shared_array[rand() % 64];
    int b = shared_array[rand() % 64];
}

My question is: How can I fetch a value from memory and be sure that the compiler is not optimizing it by removing these instructions, given that in my test I am doing nothing with those values. Even if I add an operation int v = a + b, again v is not used anywhere else, so it could be ignored.

I am using gcc with -O3, and I need to do it that way to be able to compare it against results from another source.


Solution

  • The typical way you force the compiler to actually read an otherwise unused variable is to make it volatile. This should guarantee the compiler actually read/write the variable from RAM when it is used.