Prevent consecutive read operations from memory in C from being optimized away

67 views Asked by At

My goal is to iterate memory on a microcontroller in C, and do two consecutive read operations on each cell, testing if both are zero. I try to do this as follows:

volatile uint8_t* memory = MEMORY_START_ADDR;

for(uint8_t byte = 0; byte < MEM_SIZE_IN_BYTES; byte ++)
{
      if(memory[byte] != 0) do_something();
      if(memory[byte] != 0) do_something();  // check same location again
}

Now I want to make sure that the second read operation is not optimized away by the compiler.

From my understanding, writing volatile uint8_t * memory = ... marks the object *memory as volatile, so two accesses at least to memory[0] shouldn't be optimized away. Does that also apply for all consecutive accesses to *(memory + byte)?

0

There are 0 answers