What is the point of creating a new typedef for each variable?

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

As a 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 is the point of even renaming unsigned int to size_t ? Such things often make code more difficult to understand because they force the developer to look for these type declarations in order to understand, even if it is a base type, renamed, or perhaps some class / structure. However, I see that a lot has been done in different libraries.

+4
source share
4 answers

What is the point of even renaming unsigned int to size_t? Such things often make code difficult to understand.

  • This makes it easier to understand the code, you immediately know what the object represents, "it's some size." Compare this to a bare int . The real base type is not a big concern: until you know that your code remains portable

  • Today it may be unsigned int , but perhaps tomorrow it will be unsigned long long . As long as your program uses the correct types, it is reliable for the future.

they force the developer to search for type declarations

Do not look: you will be tempted to do intolerable things with him. Think of it the way you think of C ++ std::string . You know what he does, you know how to use it, but you really don’t know what is inside.

+14
source

size_ t is used to provide portability . size_t not always "unsigned int", but it is the size that can be the maximum possible object on this platform.

+11
source

For a low-level library, such as the standard C library, typedef important for increasing the mobility of user programs; no discussion.

Using an alias in your programs, on the other hand, is an interesting question. There are two reasons:

  • to simplify your expressions, for example. pointer to a function or aggregation;
  • to introduce an abstraction.
+2
source

The reason is that types can give you a clearer idea of ​​what a variable represents. Instead of seeing a bunch if ints laying around, types like std :: size_t, std :: ptrdiff_t etc., tell us more about what happens.

0
source

All Articles