Why so many custom data types in C?
Asked Answered
P

2

5

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.

Prostate answered 24/9, 2018 at 10:12 Comment(5)
Many types show intent, which is important to make code easy to read, understand and maintain.Periderm
There are no custom data types in C. typedef does not create a new data type, but an alias. And a type is not a variable.Tribesman
Note that socklen_t and ssize_t are not standard C, they are defined by non-standard libraries.Lenna
If you find the names in C too many" already, you should never look at the language and standard libraries of Python, C++ or most other languages. Instead of learning every name, it's better to understand the idea and (if any) naming convention. Expecially for fixed-/least-/… width names it's very easy.Tribesman
socklen_t and ssize_t are defined in the POSIX.1 standard. It is different to the C standard, but its System Interfaces section describes features and facilities provided by a POSIX-compatible standard C library. This is the standard that defines sockets, signals, directory tree scanning, and so on. This means that OP needs to add the posix tag, to get a proper answer.Metcalfe
D
4

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.

Douala answered 24/9, 2018 at 10:24 Comment(1)
I don't understand "Now if we just write unsigned n then size of n may be less than 32 bits."Blanc
T
2

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.

Twobyfour answered 24/9, 2018 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.