In C++, the struct keyword is used to define a structure, which is a data type that can contain multiple different types of data. The
typedef keyword is used to create an alias for a data type.
The main difference between struct and typedef struct is that
struct defines a new data type, while typedef struct simply creates an alias for an existing data type. This means that you can use a
struct to declare variables, while you can only use a typedef struct to refer to a variable that has already been declared using a
struct.
For example, the following code defines a struct called Point:
C++
struct Point {
int x;
int y;
};
The following code declares a variable of type Point:
C++
Point point;
The following code declares a typedef called Point that refers to the
struct of the same name:
C++
typedef struct Point Point;
The following code declares a variable of type Point:
C++
Point point;
In both cases, the variable point will be of type Point. However, the first code defines a new data type called
Point, while the second code simply creates an alias for the existing data type
struct Point.
In general, you should use struct if you want to define a new data type. You should use
typedef struct if you want to refer to an existing data type without having to write out the full name of the data type every time you want to use it.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C++, the
structkeyword is used to define a structure, which is a data type that can contain multiple different types of data. Thetypedefkeyword is used to create an alias for a data type.The main difference between
structandtypedef structis thatstructdefines a new data type, whiletypedef structsimply creates an alias for an existing data type. This means that you can use astructto declare variables, while you can only use atypedef structto refer to a variable that has already been declared using astruct.For example, the following code defines a
structcalledPoint:C++
The following code declares a variable of type
Point:C++
The following code declares a
typedefcalledPointthat refers to thestructof the same name:C++
The following code declares a variable of type
Point:C++
In both cases, the variable
pointwill be of typePoint. However, the first code defines a new data type calledPoint, while the second code simply creates an alias for the existing data typestruct Point.In general, you should use
structif you want to define a new data type. You should usetypedef structif you want to refer to an existing data type without having to write out the full name of the data type every time you want to use it.