Why are types always a certain size no matter its value?

后端 未结 19 1882
谎友^
谎友^ 2021-01-30 15:22

Implementations might differ between the actual sizes of types, but on most, types like unsigned int and float are always 4 bytes. But why does a type always occupy a certai

19条回答
  •  终归单人心
    2021-01-30 16:11

    Java uses classes called "BigInteger" and "BigDecimal" to do exactly this, as does C++'s GMP C++ class interface apparently (thanks Digital Trauma). You can easily do it yourself in pretty much any language if you want.

    CPUs have always had the ability to use BCD (Binary Coded Decimal) which is designed to support operations of any length (but you tend to manually operate on one byte at a time which would be SLOW by today's GPU standards.)

    The reason we don't use these or other similar solutions? Performance. Your most highly performant languages can't afford to go expanding a variable in the middle of some tight loop operation--it would be very non-deterministic.

    In mass storage and transport situations, packed values are often the ONLY type of value you would use. For example, a music/video packet being streamed to your computer might spend a bit to specify if the next value is 2 bytes or 4 bytes as a size optimization.

    Once it's on your computer where it can be used though, memory is cheap but the speed and complication of resizable variables is not.. that's really the only reason.

提交回复
热议问题