Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty structure in C

Tags:

c

struct

warnings

I have a structure with no members (for the moment) and I would like to know if it is possible to suppress the warning I get:

warning: struct has no members

Is it possible to add a member and keep the sizeof the struct zero? Any other solution?

like image 383
claf Avatar asked Apr 16 '09 09:04

claf


People also ask

Can we have empty structure in C?

It's worth noting that empty structs are only somewhat supported in C and disallowed in C99. Empty structs are supported in C++ but different compilers implement them with varying results (for sizeof and struct offsets), especially once you start throwing inheritance into the mix.

What is an empty structure?

The empty struct is a struct type that has no fields. Here are a few examples in named and anonymous forms type Q struct{} var q struct{}

What is the use of empty structure?

Very useful in channels when you notify about some event but you don't need to pass any information about it, only a fact. Best solution is to pass an empty structure because it will only increment a counter in the channel but not assign memory, copy elements and so on.

What is size of empty struct in C?

Sizeof empty struct is 0 byte in C but in C++ it is 1 byte.


2 Answers

In c the behaviour of an empty structure is compiler dependent versus c++ where it is part of the spec (explanations here)

C++
A class with an empty sequence of members and base class objects is an empty class. Complete objects and member subobjects of an empty class type shall have nonzero size.

in C it is rather more murky since the c99 standard has some language which implies that truly empty structures aren't allowed (see TrayMan's answer) but many compilers do allow it (e.g gcc).

Since this is compiler dependent it is unlikely that you will get truly portable code in this case. As such non portable ways to suppress the warning may be your best bet.

  • In VS you would use #pragma warning
  • in GCC from 4.2.1 you have Diagnostic Pragmas
like image 155
ShuggyCoUk Avatar answered Sep 23 '22 07:09

ShuggyCoUk


if you just need the struct symbol for casting and function arguments then just:

typedef struct _Interface Interface;

this will create the symbol for an opaque type.

like image 43
ebassi Avatar answered Sep 22 '22 07:09

ebassi