- In both C and C++, the struct definition is the same:
struct Student
{
char firstName[20];
char lastName[20];
int studentID;
double gpa;
};
- But in C++, the structure "tag" (or name) is now a new type. In
C, we still have to use struct when declaring a variable or a
function prototype:
Student s1, s2, s3; // C++ declaration of Student variables
void Print(Student s); // C++ function prototype
struct Student s1, s2, s3; // C declaration of Student variables
void Print(struct Student s); // C function prototype
- However, in C you can make a single word as a new type name for a
struct type by using a typedef statement:
typedef struct student // this is the structure "tag"
{
char firstName[20];
char lastName[20];
int studentID;
double gpa;
} Student; // this is now the new type name
struct student s1; // C declaration using regular "tag"
Student s2; // C declaration using new type name
- The same thing goes for enumerations, with the keyword enum
enum Suit {CLUBS, HEARTS, DIAMONDS, SPADES};
Suit s; // C++ declaration. Suit is now a type
enum Suit s; // C declaration of the same thing
- Using typedef in C for an enum:
typedef enum suit {CLUBS, HEARTS, DIAMONDS, SPADES} Suit;
enum suit s1; // Regular C declaration (using "tag")
Suit s2; // C declaration using new type name