The difference between "structure" and "typedef structure"

Asked 2 years ago, Updated 2 years ago, 134 views

What's the difference between these two in C++?

Most of them use the second method Why is that?

c++ struct typedef

2022-09-22 22:32

1 Answers

C++'s structure/union/enum/class is all internally typedef. So in C++, there's not much difference between the two methods.

C는 그렇지 않기 때문에 두 방법이 차이가 있지요.

Please note that there are two types of C namespace. Because these two are different namespaces, overlapping names do not cause conflicts.

In the following code, Foo is defined only in tag namespace x1 cannot be compiled.

struct Foo { ... };
Foox1; //compilation error
structureFoox2; // Compileable

However, whenever I have to write Foo, it is very annoying to write structure Foo. So, use the typedef keyword and put Foo in typedef namespace.

struct Foo { ... };
typedef struct Foo Foo;

//or shorten the code above
typedef struct Foo { ... } Foo;

With the addition of typedef, structure Foo (tag namespace) and Foo (typedef namespace) are now the same. From now on, you don't have to put the structure keyword in front of you.

typedef struct { ... } Foo; creates typedef on unnamed structures. This does not register with tagnamespace but only with typedefnamespace.


2022-09-22 22:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.