Coding Style in STM32 HAL Code – Best Practices

chal-librarystm32

While I was reading the STM32 HAL drivers for timers I found this macro:

#define __HAL_TIM_DISABLE(__HANDLE__) \
                    do { \
                      if (((__HANDLE__)->Instance->CCER & TIM_CCER_CCxE_MASK) == 0U) \
                      { \
                        (__HANDLE__)->Instance->CR1 &= ~(TIM_CR1_CEN); \
                      } \
                    } while(0)

Since the while part is always wrong there should be basically no loop, and the do-while seems redundant to me. But since they distribute it in the HAL like this, I suppose there is some point? Can anyone point out which?

Best Answer

A do { something; } while (0) is a typical pattern in macros, where you want to make sure that all instructions get executed.

Example why this is important:

#define MY_MACRO() do_something1(); do_something2()

This will work:

MY_MACRO();

but this will not work as intended:

if (some_condition) MY_MACRO();

because it will be preprocessed into:

if (some_condition) do_something1(); do_something2();

The second statement will be executed no matter what the condition said.

A do { ... } while(0) is just a convenient way to make a block of code. It will be optimized out by the compiler anyway, so there is actually no looping involved and no runtime overhead.

Related Topic