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.

user107224
  • 207
  • 1
  • 12
Danilo Gacevic
  • 384
  • 2
  • 9
  • 3
    Many types show *intent*, which is important to make code easy to read, understand and maintain. – Some programmer dude Sep 24 '18 at 10:15
  • 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. – too honest for this site Sep 24 '18 at 11:20
  • 1
    Note that socklen_t and ssize_t are not standard C, they are defined by non-standard libraries. – Lundin Sep 24 '18 at 11:47
  • 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. – too honest for this site Sep 24 '18 at 12:32
  • socklen_t and ssize_t are defined in the [POSIX.1](http://pubs.opengroup.org/onlinepubs/9699919799/) 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 [tag:posix] tag, to get a proper answer. – Nominal Animal Sep 24 '18 at 22:52

2 Answers2

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.

taskinoor
  • 43,612
  • 11
  • 111
  • 136
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.

user0x0
  • 253
  • 1
  • 7