Question

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.

Était-ce utile?

La 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.

Autres conseils

Use a and b in a function that is not defined in your current compilation unit (source file).

The keyword volatile tells the compiler to not optimize that code. This applies for both variables and functions. You can even do this on inline assembly, which is a more advanced topic. See this question.

It is usually applied after the type specifier, e.g. int volatile i = 0;.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top