1

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)?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Cramstyler
  • 65
  • 4
  • 1
    In this case nothing would be optimized away even if `memory` is not volatile. And practically there should be no undefined behaviour here, at least I'm not aware of any C compiler that would do that. – Jabberwocky Jan 18 '22 at 15:36
  • @Jabberwocky I assumed that would be a perfect example for compiler optimization, no? Two consecutive reads on a location that does not seem to change in between. – Cramstyler Jan 18 '22 at 15:41
  • 1
    @Cramstyler oh, sorry, I misread the code, you're right. But `volatile` should prevent optimisation. – Jabberwocky Jan 18 '22 at 15:43
  • @EugeneSh. I got caught as well. The inner loop reads `memory[byte]` twice in a row – Jabberwocky Jan 18 '22 at 15:43
  • @Jabberwocky Right. `volatile` is needed if one expect this memory to change by some external means – Eugene Sh. Jan 18 '22 at 15:45
  • 2
    To your question, `memory + byte` has the same type of `memory`, including the `volatile` qualifier. – Eugene Sh. Jan 18 '22 at 15:48
  • Yes, this is exactly what `volatile` is for. – Peter Cordes Jan 18 '22 at 15:48
  • @EugeneSh. Thanks, I was looking for explicit confirmation of that. :) – Cramstyler Jan 18 '22 at 15:50
  • BTW, I'd take back my comment regarding this access being undefined behavior. This location *might* contain an *object*, while C standard does not restrict the definition of *object* to objects created by the C program itself. This object may belong to the execution environment. – Eugene Sh. Jan 18 '22 at 15:59

0 Answers0