typedef in C:
typedef: The typedef stands for type definition. The typedef is a keyword used in C Programming to redefine names to the already existing variable. It provides a shortcut for multiple variables to declare their data type.
Syntax of typedef in C:
typedef data_type existing_name name1,name2.....;
typedef is a keyword used to redefine names for the existing name.
data_type is the type of the existing_name.
existing_name is the already given variable name.
name1, name2,..... are the other names given to the existing variable.
Declaring typedef in C:
typedef int var v1, v2;
(or)
typedef int var;
var v1,v2;
Note: The data type of new variables will be the existing name.
Both the above declarations are the same. In the above example, I have declared var as an existing name, and the v1, v2 are the redefined names of type int. In the second declaration, instead of declaring the type of v1, v2 I have declared var as its type.
We can also write the above declaration as:
int v1, v2;
The typedef keyword is useful when we are dealing with large data types such as structures, unions, and pointers.
Example: Let's see a simple example of a typedef keyword.
Program:
Output:
Explanation: In the above example, I have declared an existing variable as a score. The redefined variables as s1 and s2. Make sure the type of new variables will be the existing name. These variables are initialized with s1=10 and s2=20.
Using typedef with structures:
Example: Let's see the structure example with typedef.
Program:
Output:
Explanation: In the above example, the typedef keyword is used to define the structure, emp is declared as a structure variable or we can call it a typedef existing name. With the help of the existing name, we have created a new name e1. BY using e1 we have initialized the structure members. We have used the dot(.) operator to access the members of the structure.
typedef with Pointers:
Example: Let's see a simple example of typedef using pointers.
Program:
Output:
Explanation: In the above example, the pointer variable ptr is declared using typedef. The redefined two pointers are p1,p2. To store the address of another variable, ma and n are initialized. Address(&) operator is used to store the location address of the variable. Indirection operator(*) is used to print the value stored at the address location.
In this tutorial, you have learned how to create a new name for the existing name using the C typedef keyword.
prev<---Enum in C Next Topic--->File I/O
No comments:
Post a Comment