Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

compiler construction - What is the size of an empty struct in C?

According to me, it is zero but there seems to be bit confusion here

I have tested it with gcc compiler and it gives me zero as output. I know that in C++, size of an empty class is 1. Let me know if I am missing anything here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A struct cannot be empty in C because the syntax forbids it. Furthermore, there is a semantic constraint that makes behavior undefined if a struct has no named member:

struct-or-union-speci?er:
  struct-or-union identi?eropt { struct-declaration-list }
  struct-or-union identi?er

struct-or-union:
  struct
  union

struct-declaration-list:
  struct-declaration
  struct-declaration-list struct-declaration

struct-declaration:
  speci?er-quali?er-list struct-declarator-list ;

/* type-specifier or qualifier required here! */
speci?er-quali?er-list:
  type-speci?er speci?er-quali?er-listopt
  type-quali?er speci?er-quali?er-listopt

struct-declarator-list:
  struct-declarator
  struct-declarator-list , struct-declarator

struct-declarator:
  declarator
  declaratoropt : constant-expression

If you write

struct identifier { };

It will give you a diagnostic message, because you violate syntactic rules. If you write

struct identifier { int : 0; };

Then you have a non-empty struct with no named members, thus making behavior undefined, and not requiring a diagnostic:

If the struct-declaration-list contains no named members, the behavior is unde?ned.

Notice that the following is disallowed because a flexible array member cannot be the first member:

struct identifier { type ident[]; };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...