Code:
typedef signed short SIGNED_SHORT; //16 bit
typedef signed int SIGNED_INT; //32 bit
SIGNED_SHORT x;
x = (SIGNED_SHORT)(SIGNED_INT) 45512; //or any value over 32,767
Here is what I know:
Signed 16 bits:
Signed: From −32,768 to 32,767
Unsigned: From 0 to 65,535
Don’t expect 45512 to fit into x as x is declared a 16 bit signed integer.
How and what does the double casting above do?
Thank You!
These
typedefs are not particularly useful. A typedef does nothing more than provide a new name for an existing type. Typesigned shortalready has a perfectly good name: “signed short“; calling itSIGNED_SHORTas well doesn’t buy you anything. (It would make sense if it abstracted away some information about the type, or if the type were likely to change — but using the nameSIGNED_SHORTfor a type other thansigned shortwould be extremely confusing.)Note also that
shortandintare both guaranteed to be at least 16 bits wide, andintis at least as wide asshort, but different sizes are possible. For example, a compiler could make bothshortandint16 bits — or 64 bits for that matter. But I’ll assume the sizes for your compiler are as you state.In addition,
signed shortandshortare names for the same type, as aresigned intandint.A cast specifies a conversion to a specified type. Two casts specify two such conversions. The value
45512is converted tosigned int, and then tosigned short.The constant
45512is already of typeint(another name forsigned int), so the innermost cast is fairly pointless. (Note that ifintis only 16 bits, then45512will be of typelong.)When you assign a value of one numeric type to an object of another numeric type, the value is implicitly converted to the object’s type, so the outermost cast is also redundant.
So the above code snippet is exactly equivalent to:
Given the ranges of
intandshorton your system, the mathematical value45512cannot be represented in typeshort. The language rules state that the result of such a conversion is implementation-defined, which means that it’s up to each implementation to determine what the result is, and it must document that choice, but different implementations can do it differently. (Actually that’s not quite the whole story; the 1999 ISO C standard added permission for such a conversion to raise an implementation-defined signal. I don’t know of any compiler that does this.)The most common semantics for this kind of conversion is that the result gets the low-order bits of the source value. This will probably result in the value
-20024being assigned tox. But you shouldn’t depend on that if you want your program to be maximally portable.