Motivation for using size_t uint32 uint64 etc

前端 未结 5 1534
南旧
南旧 2021-02-20 05:37

When I reading some code, for integer, they use bunch of different type such as size_t, uint32, uint64 etc. What is the motivation or purpose to do this? Why not ju

5条回答
  •  逝去的感伤
    2021-02-20 06:00

    There are many possible reasons for choosing an underlying type for an integer value. The most obvious one is the size of the maximum possible value that you can store -- uint32 will be able to store a number twice as large as int32, which might be desirable. int64 will be able to store a number much larger than int32 - up to 2^63 - 1 instead of 2^31 - 1.

    There are other possible reasons as well. If you're directly reading binary data from some source (file, socket, etc), it is necessary to make sure it's interpreted correctly. If someone writes a uint32 and you interpret it as an int32, it's possible that you interpret a very large positive number as a negative number (overflow).

    size_t is just a typedef for an unsigned int, usually 32-bit I believe.

提交回复
热议问题