ant2009
ant2009

Reputation: 22486

When to decide to use typedef's data types or C's built-in standard data types

gcc 4.7.2 c89

Hello,

I am using the Apache Portable Runtime and looking at their typedef's

typedef short apr_int16_t
typedef int apr_int16_t
typedef size_t apr_size_t /* This is basically the same, so what's the point */

etc.

  1. So what is the point of all this?
  2. When should you decided to use C's built-in standard data types or typedef's data types?

I just gave a example using the APR. However, I am also speaking generally as well. There is also the stdint.h header file that typedef's data types.

Many thanks for any suggestions,

Upvotes: 1

Views: 156

Answers (2)

Jay
Jay

Reputation: 24895

In my opinion, it is better to have custom defined data types for native data types of the system as it helps in clearly distingushing the size of the types.

For Ex: A long may be 32 bit or 64 bit depending on the machine in which your code runs and the way it has been built. But, if your code specifically needs a 64 bit variable, then naming it as uint_64_t or something similar will always help in associating the size clearly.

In such cases, the code be written as:

    #if _64BIT_
    typedef long uint_64_t
    #else
    typedef long long uint_64_t
    #endif

But as suggested by Mehrdad, don't use it "just for kicks". : )

Upvotes: 2

user541686
user541686

Reputation: 210445

Great question.

  1. So what is the point of all this?

    It's meant to be for abstraction, but like anything else, it is sometimes misused/overused.
    Sometimes it's necessary for backwards compatibility (e.g. typedef VOID void in Windows), sometimes it's necessary for proper abstraction (e.g. typedef unsigned int size_t), and sometimes it's completely pointless logically, but makes typing easier (e.g. typedef char const *LPCSTR in Windows).

  2. When should you decided to use C's built-in standard data types or typedef's data types?

    If it makes something easier, or if it implements a proper abstraction barrier, use it.
    What exactly that means is something you'll just have to learn over time.
    But don't use it "just for kicks"!

Upvotes: 1

Related Questions