2020-04-04 casting定义-改变形状(浇铸)

2020-04-04  本文已影响0人  鼎城宝箭

Casting in C is unique, quite unlike other languages. It is also never intelligent.

Casting in C converts values from one type to another using carefully defined rules. If you really need to know, read the standard. Otherwise the main points are:

Conversion between integer types preserve the value, if possible. If the destination has more bits this is widening and generally safe, but may involve sign extension. If narrower, bits will be lost.

Conversion between pointer types preserves the pointer value, but the results are often undefined, often non-portable and often useful for advanced scenarios.

Conversion between integer types and pointers are OK if the integer is big enough, and preserves the bit pattern (whatever that might happen to mean). If the integer is too small, the result is undefined but not useful. As a rule 'long' is wide enough for 'void *', but no guarantees! Pointers created this way may be invalid, in all kinds of interesting ways.

Conversion between float and integer types are arithmetic conversions as defined by an appropriate library routine (with truncation, not rounding).

You can cast the return value of a function to void. I never have. It does nothing.

Some casts are applied implicitly, and in some of those the compiler will issue a warning. Best to heed the warnings!

The dictionary definition for cast is best ignored, as being unhelpful. Many casts are better described by the terms conversion or coercion, so it's worth knowing those too.

----------------------------------------------------------------------------------

This part of the Webster dictionary gives the proper definition:

a : to give a shape to (a substance) by pouring in liquid or plastic form into a mold and letting harden without pressure

b : to form by this process

So, before casting, your "object" (not literally an OOP object) is in a given shape (type). When you re-cast it, that is "pour concrete" around it to make it into a new shape, that is what you do with casting. You have a number as a hexagon-shaped integer, and after casting, you will get a rectangle-shaped string.

--------------------------------------------------------------------------------------------

上一篇 下一篇

猜你喜欢

热点阅读