Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of making a new typedef for each variable?

Tags:

c++

c

typedef

The title is a little exxagerated, but I still don't understand it.

As a most basic example, take the size_t type from time.h:

size_t <...> is defined in the header file (among others) as an unsigned integral type.

What's the point of even renaming unsigned int to size_t? Such things often make the code harder to understand, because they make a developer look for those type declarations to understand even if it's a basic type renamed, or maybe some class/struct. Yet I see this being done a lot in different libraries.

like image 235
SingerOfTheFall Avatar asked Nov 27 '22 17:11

SingerOfTheFall


1 Answers

What's the point of even renaming unsigned int to size_t? Such things often make the code harder to understand

  1. It makes code easier to understand, you immediately know what the object represents, "it's some sort of size". Compare that to a bare int. The real underlying type is of no immediate concern: as long as you don't know it your code remains portable

  2. Today it may be an unsigned int but maybe tomorrow it's going to be an unsigned long long. As long as your program uses the right types it's future-proof

they make a developer look for those type declarations

Don't look: you'll be tempted to do non-portable things with it. Think of it the way you'd think of a C++ std::string. You know what it does, you know how to use it but you don't really know what's inside.

like image 82
cnicutar Avatar answered Dec 18 '22 04:12

cnicutar