Timeline for How does casting really work for primitive data types?
Current License: CC BY-SA 4.0
10 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
May 15, 2019 at 22:05 | comment | added | Yuval Filmus | Anybody’s welcome to write their own answer... | |
May 15, 2019 at 22:00 | comment | added | Gilles 'SO- stop being evil' |
(cont.) Promotion is a technical term for certain automatic conversions. (A conversion is basically an implicit cast, and a cast is basically an explicit conversion.) There is no casting between 'A' and 65 : both are literals of type int . When casting a signed integer to an unsigned integer, the value and (on virtually all implementations) the bit pattern are preserved only if the value is non-negative.
|
|
May 15, 2019 at 21:58 | comment | added | Gilles 'SO- stop being evil' | Plenty of things are misleading or inaccurate in this answer. You're describing a sort of idealized 1970s C on a typical byte-oriented machine, but modern compilers have optimizations that make the semantics of practical-C a lot more subtle, while remaining compliant with the semantics defined by the C standard. “Casting does absolutely nothing” is wrong by any perspective. Between integer types of different ranges, it can apply a modulo operation (or sometimes other effects). When floating point is involved, it can approximate. | |
S May 15, 2019 at 21:41 | history | suggested | z3p5e6 | CC BY-SA 4.0 |
Clean up some typos.
|
May 15, 2019 at 20:56 | review | Suggested edits | |||
S May 15, 2019 at 21:41 | |||||
May 15, 2019 at 19:03 | comment | added | Yuval Filmus | The main point is that datatypes are an artificial construct. Down below it's just bits. Only the program can give them meaning. | |
May 15, 2019 at 19:02 | comment | added | user2357112 | (We don't have to worry about offset binary in our timeline, and it's forbidden by the C standard, but if things had played out differently, we could have had to deal with integer formats where the signed and unsigned representations of the same nonnegative number don't match.) | |
May 15, 2019 at 19:02 | comment | added | user2357112 | "Casting does absolutely nothing" is too broad a statement to lead with. It only does nothing for this particular cast, and only because of the signed and unsigned integer representations we've chosen. Especially for integer->floating or floating->integer casts, the new and old bit patterns in memory could be completely different. If offset binary had somehow become the standard for signed integers, unsigned->signed and signed->unsigned would change the bit pattern too. | |
May 15, 2019 at 15:31 | vote | accept | TVSuchty | ||
May 15, 2019 at 15:23 | history | answered | Yuval Filmus | CC BY-SA 4.0 |