Is static_cast(-1) the right way to generate all-one-bits data without numeric_limits?

后端 未结 5 1700
温柔的废话
温柔的废话 2021-02-05 03:28

I\'m writing C++ code in an environment in which I don\'t have access to the C++ standard library, specifically not to std::numeric_limits. Suppose I want to implem

5条回答
  •  春和景丽
    2021-02-05 03:44

    Another way is

    static_cast(-1ull)
    

    which would be more correct and works in any signed integer format, regardless of 1's complement, 2's complement or sign-magnitude. You can also use static_cast(-UINTMAX_C(1))

    Because unary minus of an unsigned value is defined as

    The negative of an unsigned quantity is computed by subtracting its value from 2^n, where n is the number of bits in the promoted operand."

    Therefore -1u will always return an all-one-bits data in unsigned int. ll suffix is to make it work for any types narrower than unsigned long long. There's no extended integer types (yet) in C++ so this should be fine

    However a solution that expresses the intention clearer would be

    static_cast(~0ull)
    

提交回复
热议问题