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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The value of an unsuffixed decimal constant such as
2147483648depends 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:
intlong intunsigned long intin which it fits.
In C99 and later, it’s the first of:
intlong intlong long intin which it fits.
You didn’t tell us what implementation you’re using, but if
long intis 32 bits on your system, then2147483648will be of typeunsigned long intif you have a pre-C99 compiler, or (signed)long long intif you have a C99 or later compiler.But in your particular case:
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 typelong long int(as it must be in C99 or later, given 32-bitlong), then the value must be converted from that type tounsigned. Conversion from a signed type to an unsigned type is well defined.So if
unsignedis wide enough to represent the value2147483648, then that’s the value that will be stored inux. And if it isn’t (ifunsigned intis 16 bits, for example), then the conversion will result in0being stored inux.You can exercise some control over the type of a constant by appending a suffix to it. For example,
2147483648ULis guaranteed to be of some unsigned type (it could be eitherunsigned intorunsigned 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.