Opaque data type in C

555 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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.