typedef C
Typedef is a c/c++ programming language reserved keyword. It is used to create a
new name (alias) for existing data types or derived data type. typedef is useful in avoiding naming confusion in large c program.
Syntax
typedef data_type new_name;
Example
void main(){
typedef float DECIMAL;
DECIMAL PI = 3.14;
}
float is given new and meaningful name DECIMAL, now, in above program, DECIMAL can used in place of float.
When to use Typedef
Use typedef to make complex declaration easier to understand. It makes a large and complex program easier to understand.
With what types Typedef can be used
Typedef can be used with built-in data types, arrays, structs, pointers or functions.
Typedef with primitive data types
void main()
{
typedef unsigned char uchar;
uchar c = 'a';
}
Typedef with Pointers
void main()
{
typedef float* PtrFlt;
PtrFlt PI = 3.14, CM = 22.57;
}
Typedef with structure
typedef struct {
int speed;
int average;
} car;
void main()
{
typedef car mycar;
mycar.speed = 20;
mycar.average = 10;
}
Typedef with Union
typedef union {
int a;
int b;
} vehicle;
void main()
{
typedef vehicle car;
car.a = 20;
car.b = 10;
}