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:
This will work:
but this will not work as intended:
because it will be preprocessed into:
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.