Thursday, November 30, 2023

Difference between 'struct' and 'typedef struct' in C++

 

In C++ there is a subtle difference between.
struct Foo { ... };
and
typedef struct { ... } Foo;

In C++ there are few types of identifiers. 
  • Constants 
  • Variables 
  • Functions 
  • Labels 
  • Defined data types 

 These identifiers are stored in different namesapces. If someone write following, he would get an compiler error.
 
struct Foo { ... }; Foo x;

That is because Foo is stored only in namespace for defined data types. 
So, everytime you need to declare an object of Foo, you need to write struct Foo x;

But with following code Foo will be defined in namesapce for variables .
 
struct Foo { ... };
typedef struct Foo Foo;

In short, It can be written as follows.
 
typedef struct Foo { ... } Foo;

So with typedef we can create objects with Foo x;
So we dont have to use struct Foo x; pattern every time we create an object of Foo.

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...