Why are there so many custom data types like socklen_t, ssize_t, size_t, uint16_t? I don't understand the real need for them. To me, they’re just a bunch of new variable names to be learned.
Intent and portability.
For example, let's say I have a variable unsinged n
. An unsigned integer can represent many things, so it's intent is not clear. But when I write size_t n
, it is clear that n
represents size of something. When I write socklen_t n
it is clear that n
represents the length of something related to socket.
Second reason is portability. For example, socklen_t
is guaranteed to be at least 32 bits. Now if we just write unsigned n
then size of n
may be less than 32 bits. size_t
can hold the size of any object, but the actual value is implementation defined. When we use plain integer it may happen that sizeof(int)
can't hold the size of largest object that is theoretically possible. But using size_t
doesn't have such portability issue.
uint16_t
clearly says that it is unsigned integer of 16 bits which is both clear and portable than using unsigned int
or unsigned short
.
Firstly, It provides more readability.
Secondly, while programming for embedded systems or cross platform or when portability is important, it is necessary of be explicit about the size of the data type that you are using - using these specific data types avoids confusion and guaranteed to be having the defined data width.
© 2022 - 2024 — McMap. All rights reserved.
typedef
does not create a new data type, but an alias. And a type is not a variable. – Tribesman