Search code examples
cnarrowing

If I bound the value of a variable with an operation like `min`, am I safe to make a narrowing conversion?


For example, say I have the following code:

#include <stdint.h>
#define MAX_SIZE 0x10000000
#define min(a,b) (((a) < (b)) ? (a) : (b))

extern uint64_t external_uint64_t;
...


uint64_t wide = min(external_uint64_t, MAX_SIZE);
uint32_t narrow = (uint32_t) wide;

Is this well defined and guaranteed to initialize narrow with the smallest of the values between external_uint64_t, and MAX_SIZE?


Solution

  • Is this well defined and guaranteed to initialize narrow with the smallest of the values between external_uint64_t, and MAX_SIZE?

    For unsigned numbers it is well defined by the C standard, but if the result of min will not fit into the unsigned integer type it will be converted the way described in the C standard.

    6.3.1.3 Signed and unsigned integers

    • 1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
    • 2 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.60)