Skip to main content
JHarm.1
Associate
April 26, 2022
Solved

Why does a condition always evaluate to be true?

  • April 26, 2022
  • 2 replies
  • 1503 views

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!

    This topic has been closed for replies.
    Best answer by JHarm.1

    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.

    2 replies

    ST Employee
    April 26, 2022

    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
    JHarm.1AuthorBest answer
    Associate
    April 26, 2022

    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.