Search code examples
cconstantsunsignedsigned

Type of constant in "unsigned ux = 2147483648;"


If I write this declaration:

unsigned ux = 2147483648;

(231), will the C compiler treat 2147483648 as an unsigned or signed value?

I've heard that constant values are always treated as signed, but I don't think that's always right.


Solution

  • The value of an unsuffixed decimal constant such as 2147483648 depends on the value of the constant, the ranges of the predefined type, and, in some cases on the version of the C standard you're using.

    In C89/C90, the type is the first of:

    • int
    • long int
    • unsigned long int

    in which it fits.

    In C99 and later, it's the first of:

    • int
    • long int
    • long long int

    in which it fits.

    You didn't tell us what implementation you're using, but if long int is 32 bits on your system, then 2147483648 will be of type unsigned long int if you have a pre-C99 compiler, or (signed) long long int if you have a C99 or later compiler.

    But in your particular case:

    unsigned ux = 2147483648;
    

    it doesn't matter. If the constant is of type unsigned int, then it's already of the right type, and no conversion is necessary. If it's of type long long int (as it must be in C99 or later, given 32-bit long), then the value must be converted from that type to unsigned. Conversion from a signed type to an unsigned type is well defined.

    So if unsigned is wide enough to represent the value 2147483648, then that's the value that will be stored in ux. And if it isn't (if unsigned int is 16 bits, for example), then the conversion will result in 0 being stored in ux.

    You can exercise some control over the type of a constant by appending a suffix to it. For example, 2147483648UL is guaranteed to be of some unsigned type (it could be either unsigned int or unsigned long int).

    Incidentally, your question's title is currently "About Class Cast.(if I write unsigned ux=2147483648(2 to the 31 st))", but your question has nothing to do with classes (which don't exist in C) or with casts. I'll edit the question.