Using constants and their associated modifiers using gcc

前端 未结 3 441
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-24 00:01

I was not sure what to call these flags, but what I am referring to is:

#define TEST_DEF 50000U //<- the \"U\" here

Google searching when yo

3条回答
  •  悲&欢浪女
    2021-01-24 00:46

    There are five integer literal suffixes in C: u, l, ul, ll, and ull. Unlike nearly everything else in C they are case insensitive; also, ul and ull can be written as lu and llu respectively (however, lul is not acceptable).

    They control the type of the constant. They work approximately like this:

    literal │ type
    ────────┼───────────────────────
    500     │ int
    500u    │ unsigned int
    500l    │ long int
    500ul   │ unsigned long int
    500ll   │ long long int
    500ull  │ unsigned long long int
    

    This is only an approximation, because if the constant is too large for the indicated type, it is "promoted" to a larger type. The rules for this are sufficiently complicated that I'm not going to try to describe them. The rules for "promoting" hexadecimal and octal literals are slightly different than the rules for "promoting" decimal literals, and they are also slightly different in C99 versus C90 and different again in C++.

    Because of the promotion effect, is not possible to use these suffixes to limit constants to any size. If you write 281474976710656 on a system where int and long are both 32 bits wide, the constant will be given type long long even though you didn't say to do that. Moreover, there are no suffixes to force a constant to have type short nor char. You can indicate your intent with the [U]INT{8,16,32,64,MAX}_C macros from , but those do not impose any upper limit either, and on all systems I can conveniently get at right now (OSX, Linux), *INT8_C and *INT16_C actually produce values with type (unsigned) int.

    Your compiler may, but is not required to, warn if you write ((uint8_t) 512) or similar (where 512 is a compile-time constant value outside the range of the type. In C11 you can use static_assert (from ) to force the issue but it might be a bit tedious to write.

提交回复
热议问题