cancel
Showing results for 
Search instead for 
Did you mean: 

Why does a condition always evaluate to be true?

JHarm.1
Associate

Hello everyone,

I have an issue regarding an always true condition produced by the following code.

Since I have never run into this kind of issue with C I guess it must have something to do with the STM environment.

The condition within the if-statement evaluates to always true, even if the values `new_distance` and `old_distance` are identical.

Please let me know your thoughts.

static uint32_t old_distance = 0;
 
uint32_t new_distance = distance_m;
 
if(new_distance != old_distance)
{
    msg->hasEvent = 1;
}
 
old_distance = new_distance;

Thanks!

1 ACCEPTED SOLUTION

Accepted Solutions
JHarm.1
Associate

Hi Bruno,

thank you very much for this precise answer.

I found the issue which had absolutely nothing to do with the code. It had to do with the internal value that has been updated so quickly that every debug cycle the `hasEvent` flag was set and therefore occurring to me as a always true evaluation.

Thanks for looking into this anyway, I appreciate the quick help.

View solution in original post

2 REPLIES 2
Bruno_ST
ST Employee

Hello @JHarm.1,

This kind of situation may happen when using compiler optimization and are caching the value (in a CPU register), optimizing accesses to that value when it seem unnecessary. When peripherals (such as DMA) or multitasking/IT are modifying this value, you have to warn the compiler to re-read it, using keyword 

volatile.

BR,

Bruno

To give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.

JHarm.1
Associate

Hi Bruno,

thank you very much for this precise answer.

I found the issue which had absolutely nothing to do with the code. It had to do with the internal value that has been updated so quickly that every debug cycle the `hasEvent` flag was set and therefore occurring to me as a always true evaluation.

Thanks for looking into this anyway, I appreciate the quick help.