Reputation: 692
Alright, this is a dumb question since I've been coding in C for a while but I've never really figured it out.
C libraries love to implement their own obscure data types which generally just seem to be reimplementations of existing types (the library prompting this question was http://man7.org/linux/man-pages/man2/gettimeofday.2.html).
My question is: how on earth are you supposed to figure out what these one-off datatypes actually are? They never seem to be defined anywhere in the man pages, so short of digging deep into the source code of a header file I'm at a loss. For example, from the above mentioned man page, what is a "suseconds_t" and how, in the general case, would I figure out what that is in detail?
Upvotes: 0
Views: 207
Reputation: 8589
Most of the time you should code so that the underlying type is irrelevant. That's the idea of portable, future-proofing code. On a different platform or in an upgrade types may change and existing code should just pick that up.
There are potential flaws though. For a scalar type like susecond
as provided you may need to output it and the library should provide a PRI
-style macro for output and a SCN
-style macro for reading. See <inttypes.h>
.
Otherwise you eventually have to come to concrete types.
These macros (or equivalent) are rarely defined (in my experience) and you have to deal with the implementation type at some point...
Also where not using generics (which are newish in C) and without C++ overloading you can hit trouble when passing values into other functions.
You call a function taking an int
and then the library or platform changes and the underlying type of susecond
is long
and boom you've introduced a quiet truncation error! Always enable all your warnings!
Your IDE might let you hover over and look up the underlying type on the boundaries where you need it. But where possible just declare types to be susecond
and let the compiler worry about it.
The reason it's done in this case is because (I guess) on 16-bit platforms int
might not do for a value up to 999,999 (microseconds...) and this needs to be long
but on 32-bit platforms where int
is likely to be 32-bt it's fine.
16-bit? Are you sure Granddad? The library is not new and may well be portable to embedded systems where 16-bit is a perfectly reasonable thing to encounter.
Upvotes: 0
Reputation: 20392
suseconds_t
is a signed integer type that can fit the number of microseconds in a second. The type is suseconds_t
, not anything else. The whole point of those "obscure" types is to make you use them instead of thinking "oh, I'll just use int because that's what I always use" and then your program becomes non-portable on some other machine or some time in the future.
Your slightly condescending tone in "C libraries love to..." is quite misguided. This is not some obscure library doing some obscure little funny thing. This is POSIX.
Upvotes: 2