what is an interface in c
An “interface” in C (unlike in C++/Java/C#) is not a built‑in language feature, but a design pattern you create using function pointers and structs.
Core idea in plain words
In C, an interface is usually:
- A
structthat holds a set of function pointers (and sometimes metadata).
- A convention: “Any module that wants to be considered a Foo must provide functions matching these signatures and fill this struct correctly.”
So it’s a way to define a contract of behavior, even though C itself
doesn’t have interface syntax like Java or C#.
Mini example: “Shape” interface in C
You might define a “shape interface” as:
c
typedef struct Shape Shape; // forward declaration
typedef struct {
double (*area)(Shape *self);
void (*draw)(Shape *self);
} ShapeVTable;
struct Shape {
const ShapeVTable *vtable;
/* common data or a void* to implementation data */
};
Each concrete type (e.g., Circle, Rectangle) provides implementations:
c
double circle_area(Shape *self);
void circle_draw(Shape *self);
static const ShapeVTable circle_vtable = {
.area = circle_area,
.draw = circle_draw
};
Any code that takes a Shape * and calls shape->vtable->area(shape) is
working through the interface , without knowing whether it’s a circle or
rectangle.
Why people call this an “interface” in C
Developers borrow the word “interface” from object‑oriented programming, where an interface is a set of method signatures that types must implement. In C, you simulate that idea by:
- Grouping related behavior into a struct of function pointers.
- Making all “implementations” fill that struct with the right functions.
- Writing code against the function‑pointer table, not concrete types.
This gives you:
- Polymorphism (different types, same API).
- Loose coupling (caller doesn’t depend on concrete implementation).
- Testability (you can plug in mock implementations easily).
Quick scoop style summary
- C has no native
interfacekeyword. - You build interfaces yourself using
struct + function pointersconventions.
- The interface is really a contract of function signatures that modules agree to implement.
- This is widely used in C libraries, drivers, and plugin systems to get OO‑like behavior.
TL;DR: In C, an “interface” is just a pattern: a struct of function pointers that defines what operations something must support, and any implementation fills that struct with its own functions.
Meta note (for your SEO / blog post needs):
Your focus keyword “what is an interface in c” naturally fits if you explain
that C doesn’t have native interfaces, but you can implement an interface‑like
contract via structs of function pointers and call that an interface pattern.