Simple
Simple

Reputation: 14390

Opaque data type in C

What is the preferred way in C to return an opaque data type?

/* Option #1: */
struct widget;
struct widget *foo();

/* Option #2: */
struct widget
{
    struct widget_impl *impl;
};
struct widget foo();

Are there any other options which are more idiomatic?

Upvotes: 2

Views: 557

Answers (1)

Jacob Pollack
Jacob Pollack

Reputation: 3751

It's a good question and there is no correct answer, both options achieve the same result however from my experience option 1 is more common.

Differences:

Option 1 is more space efficient by a minimum of a size of a pointer on your environment. Note the mention of "minimum". If you had extra fields in your wrapper structure widget that contained other useful information then not returning a pointer to a struct widget in foo will become extremely space inefficient.

Practical Uses:

Option 1 is used when you are only dealing with one structure. For example, implementing a structure to hold a point on the Euclidean plane or while implementing a dynamic array.

Option 2 is can be seen while implementing ADTs. You often need a wrapper structure to contain extra fields and hence implicitly using option 2.

Upvotes: 1

Related Questions