Struct and union name collision

I wrote a simple test program and tried to use it:

union FLT { ... };
struct FLT { ... };

      

But the compiler complained about a name clash.

Since in C you need to use struct

and union

for your tag name, why do they clash?

I mean when we want to declare a variable of a type stuct FLT

with a name num

, we will use

struct FLT num;

      

and when we want to use a variable with a diffnum

type name union FLT

, we will use

union FLT diffnum;

      

So why couldn't the compiler tell them apart?

BTW I've tested both MinGW and VC if you need to know.

UPDATE

union FLOAT {
        float value;
        unsigned int bits;
        unsigned char bytes[4];
};
struct FLOAT {
        unsigned int sign;
        unsigned int exponent;
        unsigned int significand;
};
union FLOAT num;
struct FLOAT num_parts;

      

I have used this code to do floating point arithmetic tests.

+3


source to share


1 answer


They clash because all tagged tags share the same namespace for tags.

C11 6.2.3 Identity Identifier Spaces (N1570 Project)



If more than one declaration of a specific identifier is visible at any point in translation units, the syntactic context is ambiguous which refer to different objects. Thus, there is a separate name for spaces for different categories of identifiers:

  • label names (ambiguous by the syntax of label declaration and use);
  • structure, union and enumeration tags (ambiguous, using any of the keywords struct, union, or enum);
  • members of structures or unions; each structure or union has a separate namespace for its members (the type of expression used to access an element via. or β†’ is ambiguous);
  • all other identifiers called regular identifiers (declared in regular declarators or enumeration constants).
+6


source







All Articles