Skip to content

Instantly share code, notes, and snippets.

@kshenoy
Created July 12, 2012 01:34
Show Gist options
  • Select an option

  • Save kshenoy/3095062 to your computer and use it in GitHub Desktop.

Select an option

Save kshenoy/3095062 to your computer and use it in GitHub Desktop.
Use of typedefs with struct and enum in C/C++
// 1a) Struct declaration and instantiation w/o typedef
struct veg_t{
int cost;
char c;
};
struct veg_t potato;
// 1b) or its equivalent with declaration and instantiation combined…
struct veg_t{
int cost;
char c;
} potato;
// 2a) To avoid having to type the keyword ‘struct’ before every instantiation, typedefs were commonly used as:-
typedef struct fruit_t{
int cost;
char c;
} fruit_st;
fruit_st apple;
// 2b) This is equivalent to
struct fruit_t{
int cost;
char c;
};
typedef struct fruit_t fruit_st;
fruit_st apple;
// 2c) And can also be written as
typedef struct{
int cost;
char c;
} fruit_t;
fruit_t apple;
/*
Thus, in 1b. the word between } and ; (potato) is the name of the object
while in 2a., it represents the datatype.
In C++, appending the keyword struct is not necessary while instantiating variables thus making the use of typedef redundant.
All of the above also applies to ‘enum’
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment