Search code examples
c

Implications of explicitly casting a value to the type it gets returned as from a function?


#include <stdint.h>
uint8_t square(uint16_t num, int x) {
    return (uint8_t)(num / x);
}

Should you explicitly cast the uint16_t result to uint8_t, or let it be implicitly cast? My concerns are any speed cost, and the compiler complaining, otherwise I think this should work, even if the cast result gets truncated (which it doesn't in my case since num/x is guaranteed to fit inside uint8_t)


Solution

  • Should you explicitly cast the uint16_t result to uint8_t, or let it be implicitly cast?

    You cast int not uint16_t as uint16_t is being converted to int and then divided by int

    C standard 6.3.1.1 p.2

    If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.48) All other types are unchanged by the integer promotions.

    Then you return uint8_t. The way int is converted to uint_8 is also defined by the standard:

    Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

    My concerns are any speed cost, and the compiler complaining

    The cast does not change anything - the result will the same

    even if the cast result gets truncated (which it doesn't in my case since num/x is guaranteed to fit inside uint8_t)

    The result of your operation can be negative.