Gzorg
Gzorg

Reputation: 857

What does the colon mean in struct declarations in C?

Reading the code of TeXmacs, I saw this:

struct texmacs_input_rep : concrete_struct {
...
};

What does that mean?

This syntax is defined in the C standard, p113, but I didn't find the meaning of it, but that's because I don't know how to read grammar rules.

Because concrete_struct is another struct, that contains functions looking like a constructor and a virtual destructor, and because I read elsewhere that classes in C++ are actually struct with public members by default, I guess that this is the way of doing inheritance with struct in C (because it is the C standard...).

Is this correct?

Upvotes: 11

Views: 12056

Answers (4)

sth
sth

Reputation: 229593

It is C++ syntax and equivalent to this:

class texmacs_input_rep : public concrete_struct {
public:
...
};

This is the normal syntax for inheritance of classes, here texmacs_input_rep is inherited from concrete_struct.

About that syntax in C:

The C-Standard you linked to defines (6.7.2.1):

struct-or-union-specifier:
    struct-or-union identifieropt { struct-declaration-list }
    struct-or-union identifier

struct-or-union:
    struct
    union

So according to C it must be struct, followed by an optional identifer, followed by {. Or only struct followed by an identifer (a forward declaration). In neither case there is room for an additional : ... in there.

The : mentioned later in that paragraph of the standard is about bit-field widths, like this;

struct foo {
  unsigned a : 4;
  unsigned b : 3;
};

Here a and b are only 4 and 3 bits wide, but that's different syntax than in the question.

Upvotes: 26

unwind
unwind

Reputation: 399823

Are you sure this is C?

The standard document you linked to does not describe such a syntax, that I could see.

This looks like C++, where it indeed is used to say that the struct inherits another struct. The TeXmacs compilation page recommends you to use a C++ compiler, which (to me) implies that it's written in C++, not C.

I took a quick look in the TeXmacs source archive, and saw lots of ".cpp" files.

Upvotes: 3

246tNt
246tNt

Reputation: 2170

GCC doesn't like it (in C mode of course).

And looking at the spec, I don't see that defined at page 113 (6.7.2.1), it says :

struct-declarator:
    declarator
    declarator_opt : constant-expression

which is the syntax for bitfields like this :

struct blah {
    int a : 4;
    int b : 4;
};

So in summary: this is not C, it's C++ and it's inheritance like class inheritance.

Upvotes: 7

pmg
pmg

Reputation: 108988

The : in the text of the Standard is not part of the C construction. It is there to separate the thing being defined and its definition.

There is no valid use of the : in a struct declaration.

Upvotes: 2

Related Questions