Prev Next
- Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. This is same like defining alias for the commands.
- Consider the below structure.
struct student
{
int mark [2];
char name [10];
float average;
}
- Variable for the above structure can be declared in two ways.
1st way :
struct student record; /* for normal variable */
struct student *record; /* for pointer variable */
2nd way :
typedef struct student status;
- When we use “typedef” keyword before struct <tag_name> like above, after that we can simply use type definition “status” in the C program to declare structure variable.
- Now, structure variable declaration will be, “status record”.
- This is equal to “struct student record”. Type definition for “struct student” is status. i.e. status = “struct student”
An alternative way for structure declaration using typedef in C:
typedef struct student
{
int mark [2];
char name [10];
float average;
} status;
- To declare structure variable, we can use the below statements.
status record1; /* record 1 is structure variable */
status record2; /* record 2 is structure variable */
Example program for C typedef:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Structure using typedef: #include <stdio.h> #include <string.h> typedef struct student { int id; char name[20]; float percentage; } status; int main() { status record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); return 0; } |
Output:
Id is: 1
Name is: Raju Percentage is: 86.500000 |
- Typedef can be used to simplify the real commands as per our need.
- For example, consider below statement.
typedef long long int LLI;
- In above statement, LLI is the type definition for the real C command “long long int”. We can use type definition LLI instead of using full command “long long int” in a C program once it is defined.
Another example program for C typedef:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <stdio.h> #include <limits.h> int main() { typedef long long int LLI; printf("Storage size for long long int data " \ "type : %ld \n", sizeof(LLI)); return 0; } |
Output:
Storage size for long long int data type : 8
|