Report
4 years ago.

Won't execute code after while loop.

In the middle of a function I have a while loop that waits for interrupts until the US_count has reached 100. After this I want it to continue to execute code below.

If I just end the while loop with semicolon as below or empty brackets the code below the loop wont execute. BUT, if I have a printf like the one i have commented below the code is executed. So my question is why is that, to me this seems very strange?

void some_function(){

code

while(US_count<100); {pc.printf("something");}

code

}

Comment on this question

2 Answers

4 years ago.

A printf is a very time consuming task, is your code time dipendant?

maybe the best way to understand why is doing this is using a jtag debugger :)

4 years ago.

I am going to guess that US_count isn't defined as volatile? If that is not the case, then the compiler is not guaranteed to load the latest value from its SRAM memory in the loop, since the compiler has no way of knowing it can be modified by the interrupt. (It will think that since the value isn't changing in the loop, it does not need to read the latest value from memory).

But it depends what else it is doing in the loop: The printf also requires the usage of registers, and that probably means it has to reload the value from its SRAM into a register, making it work properly.

However the correct way to solve this is by adding the 'volatile' keyword in front of the definition of US_count, this forces the compiler to always read the last value from memory.


To post an answer, please log in.