James
James

Reputation: 1490

What does this C code mean?

I know that typedef'ing allows you to refer to a struct without using the struct keyword. However, with this:

typedef struct SYSTEM SYSTEM;

I've seen this typedef in a C API, but struct SYSTEM has not been defined previously.

In fact, a .c file containing only that line will compile by itself.

What does the compiler think SYSTEM (or struct SYSTEM) actually is?

Many thanks!

Upvotes: 2

Views: 184

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 476960

The struct doesn't need to be defined. It only needs to be declared. The typedef declaration you present subsumes the declaration of struct SYSTEM.

So it's equivalent to:

struct SYSTEM;

typedef struct SYSTEM SYSTEM;

Thanks to this typedef, SYSTEM now names an incomplete type, so you can use it like SYSTEM * in interface definitions, without needing to expose the actual definition of the struct, which can be kept private:

public_header.h:

typedef struct SYSTEM SYSTEM;

SYSTEM * create_system();

int do_useful_thing_with(SYSTEM * system, int count, void * addr);

void destroy_system(SYSTEM * system);

private_impl.c:

#include <public_header.h>

struct SYSTEM { int a; char b[12]; float q; void * next; };

SYSTEM * create_system()
{ 
    SYSTEM * p = malloc(sizeof *p);
    if (p) { p->a = 2; p->q = 1.5; }
    return p;
}

void destroy_system(SYSTEM * system)
{
    free(system);
}

// etc.

Upvotes: 5

This is a typical C construct, as opposed to C++ and Java etc, that directly define types in the global namespace. C structs cannot be accessed by their name only, so the typedef is needed to be able to call a SYSTEM just SYSTEM.

struct SYSTEM {
  ...
};
struct SYSTEM foo;   //legal
SYSTEM bar;   //illegal
typedef struct SYSTEM SYSTEM;   //give it a global name
SYSTEM baz;   //now it's legal

Upvotes: 0

PP.
PP.

Reputation: 10864

I'd say this is generally ill-advised behaviour but the gist is:

typedef type name

..where here the type is struct SYSTEM and the name assigned is SYSTEM.

Usually one would give a different name to the typedef than the type the typedef is derived from. Hence the low opinion many code maintainers might have to this kind of behaviour.

Upvotes: -1

Related Questions