When to use different integer types?

前端 未结 8 1191
猫巷女王i
猫巷女王i 2021-02-13 20:54

Programming languages (e.g. c, c++, and java) usually have several types for integer arithmetic:

  • signed and unsigned types
  • types
8条回答
  •  鱼传尺愫
    2021-02-13 21:24

    The need for different size integer types arises from two basic problems: type size pretty much needs to be known on a low level, and in the old days of memory constraints, it was important in every day usage as you had little to play with. If you're doing basic arithmetic, then it is almost unimportant as to which type you use. For example, when looping from 1 to 100, it isn't really important whether you use uint16_t or uint64_t, provided your types fit and you're using the correct type if you need/don't need signing.

    However, it becomes important when you want to scale / need to optimise. If you want to allocate 1,000,000,000 such integers, then saying "each one will be 64-bit just in case" or "I'll use the built in type" isn't going to cut it - that's 8,000,000,000 bytes which is about 7.5GB of data. Now 1 billion 64-bit integers doesn't sound feasible, but these could be points in a 3D array (1000^3), in which case you've also got pointer sizes to content with too. You could go a lot further with 8-bit integers for your values, for example. How much you can allocate then informs your algorithms - if you can't allocate that much data at once you might consider mmap or handling parts of the data at once (a.k.a. handling swapping yourself). If you don't need values of a certain size, that's when you start using more constrained types. Similarly, you get an extra power of 2 by using unsigned types. Very useful.

    If you're ever writing assembly to go along with your C/C++, then knowing the size of the data type is pretty much crucial, especially when it comes to allocating local stack space or reading variables from memory addresses (as opposed to already in a register). Think of it as programming entirely using void*. As such, I tend to use stdint.h defined types by habit, so that I'm always aware of my sizes and formats, when mixing the two.

提交回复
热议问题