Search code examples
cembeddedautosar

Seemingly pointless operations in a macro


The following macro is from an MCAL source of a microcontroller and it converts timer ticks to milliseconds.

#define TICKS2MS(x)     ( (uint64) (((((uint64)(x)) * 1) + 0) / 100000) )  

Could you please help me understand the significance of multiplying by 1 and adding 0?


Solution

  • The multiplication and addition are in fact pointless, as is the outer cast.

    Both operators perform the usual arithmetic conversions on both operands.

    For the multiplication, the left operand has type uint64 (as a result of the cast) and the right operand has type int. Since uint64 is the larger type it will be the type of the result. The operand 1 does not change value as a result of the conversion, so in multiplying by 1 the result has the same type and value as (uint64)(x).

    Similarly for the addition, the operands are of type uint64 and int respectively, meaning the resulting type is uint64, and 0 does not change value after the conversion. So by adding 0 the result has the same type and value as (uint64)(x) * 1 which has the same type and value as (uint64)(x).

    The cast at the end is also superfluous, as the casted expression already has type uint64. As above, the division operator performs the usual arithmetic conversions on its operands so dividing a uint64 by an int results in a uint64.

    So the above macro is equivalent to:

    #define TICKS2MS(x)     ((uint64)(x) / 100000)