What defines an opaque type in C, and when are they necessary and/or useful?

CTypes

C Problem Overview


I've seen the concept of 'opaque types' thrown around a bit but I really haven't found a succinct answer as to what defines an opaque type in C and more importantly what problems they allow us to solve with their existence. Thanks

C Solutions


Solution 1 - C

It is the most generally used for library purpose. The main principe behind Opaque type in c is to use data though its pointer in order to hide data handling implementation. Since the implementation is hidden, you can modify the library without recompiling any program which depend on it (if the interface is respected)

eg: version 1:

// header file
struct s;

int s_init(struct s **x);
int s_f(struct s *x);
int s_g(struct s *x);

// source file
struct s { int x; }

int s_init(struct s **x) { *x = malloc(...); }
int s_f(..) { ... }
int s_g(..) { ... }

version 2

// header file
struct s;

int s_init(struct s **x);
int s_f(struct s *x);
int s_g(struct s *x);

// source file
struct s { int y; int x; }

int s_init(struct s **x) { *x = malloc(...); }
int s_f(..) { ... }
int s_g(..) { ... }

From your program side, nothing changed! and as said previously, no need to recompile every single program which rely on it.

Solution 2 - C

In my understanding, opaque types are those which allow you to hold a handle (i.e., a pointer) to an structure, but not modify or view its contents directly (if you are allowed to at all, you do so through helper functions which understand the internal structure).

Opaque types are, in part, a way to make C more object-oriented. They allow encapsulation, so that the internal details of a type can change--or be implemented differently in different platforms/situations--without the code that uses it having to change.

Solution 3 - C

An opaque type is a type which is exposed in APIs via a pointer but never concretely defined.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSiegeXView Question on Stackoverflow
Solution 1 - CPhongView Answer on Stackoverflow
Solution 2 - CTim YatesView Answer on Stackoverflow
Solution 3 - CJaredParView Answer on Stackoverflow