Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef, structure and type compatibiliy

Tags:

c

struct

If I have these two structs:

struct
{
   int x;
} A;

struct
{
   int x;
} B;

then making A = B; results in a compilation error because the two anonymous structs are not compatible.

However if I do:

typedef struct
{
   int x;
} S;

S A;

S B;

A = B; is a legal assignment because they are compatible.

But why? With typedef I understand that the compiler makes this when meet S A and S B:

struct { int x; } A;
struct { int x; } B;

so A and B should not be compatible...

like image 440
xdevel2000 Avatar asked Sep 18 '14 08:09

xdevel2000


People also ask

What is the difference between typedef and structure?

In C++, there is no difference between 'struct' and 'typedef struct' because, in C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name.

What is a typedef structure?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.

Should you use typedef with struct?

In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.

What is the type of typedef?

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.


2 Answers

Each anonymous struct declaration is a distinct type; this is why you get a type mismatch when trying to assign one to the other.

A typedef, however, declares an alias (i.e. a new name for something that already exists) for a type (it does not create a new type).

A typedef is also not a simple text replacement, like a preprocessor macro. Your statement

I understand that the compiler make this when meet S A and S B:

struct { int x; } A;
struct { int x; } B;

is where your understanding is wrong.

When you use the type alias S, as in

S A;
S B;

the types of both objects A and B are the same by definition and assigning one to the other is possible.

like image 121
Jens Avatar answered Oct 17 '22 05:10

Jens


This is because C treats every untagged struct as a new kind of struct, regardless of the memory layout. However, typedef struct { } name; cannot be used if you want to use the struct in a linked list. You'll need to stick with defining a structure tag in this case, and typedef the tagged struct instead.

like image 4
downhillFromHere Avatar answered Oct 17 '22 05:10

downhillFromHere