typedef <existing_name> <alias_name>
Example:
typedef char word;
typedef int Int16; typedef float F32;
Then we can declare those variables like this:
Int16 age, id; F32 salary;
struct student { int id; int course_code; int section; };
We can typedef it to another name (learner).
typedef struct student learner;
struct programiz { int local_street; char *town; char *my_city; char *my_country; }; ... struct programiz var; var.town = "Agra";
typedef struct programiz{ int local_street; char *town; char *my_city; char *my_country; }addr; .. .. addr var1; var.town = "Agra";
Declaring Typedef Struct in C Example1:
Consider the following structure:
struct student { int mark [2]; char name [10]; float average; }
We can declare the above variable in two ways.
1st way:
struct student record; /* for normal variable */ struct student *record; /* for pointer variable */
2nd way:
typedef struct student status;
Example 2:
// 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, "Himu"); 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; }
When above code is executed, our output looks like−
Id is: 1 Name is: Himu Percentage is: 86.500000
We can also use typedef
with pointer
. In Pointers *
binds to the right and not on the left.
int* x, y;
Above we are actually declaring x as a pointer of type int, whereas y will be declared as a plain int variable. But if we use typedef, we can declare any number of pointers in a single statement.
typedef int* IntPtr; IntPtr x, y, z;
- #define can be used to define alias for values as well, q., you can define 1 as ONE etc. Where typedef is limited to giving symbolic names
- #define statements are processed by the pre-processor, where typedef interpretation is performed by the compiler
#include <stdio.h> #define TRUE 1 #define FALSE 0 int main( ) { printf( "Value of TRUE : %dn", TRUE); printf( "Value of FALSE : %dn", FALSE); return 0; }
When above code is executed, our output looks like−
Value of TRUE : 1 Value of FALSE : 0
If you want to more about structure in c,then just click Here. So, guys, that’s all about typedef struct in c. Later we will discuss another tutorial on c programming. Till then, take care. Happy Coding.