Difference between typedef and define in CIn this topic, we will discuss the difference between typedef and define in C programming language. typedef:A typedef is a keyword used in C programming to define a new name for exiting data types. But it cannot provide a new data type to the predefined data type. Instead, it provides a meaning full names to an already existing data type (int, char, float, etc.). It is defined outside the main() function in a program. In other words, a typedef is used to redefine the names of existing data types in C programming. Syntax In the above syntax, the existing _name defines the predefined data types or variable name. The 'alias _name' or newName defines the new name for exiting data type or variable name in the C program. Example 1: Consider a program to use the typedef keyword in C. Type.c Output: Enter the first number: 20 Enter the second number: 10 The sum of the two numbers is: 30 Example 2: Let's consider another program to use the typedef in unsigned char of C. program.c Output: Demonstrate the use of typedef Keyword Print a single Byte: D Print a single Byte: E Use of typedef keyword in StructureLet's consider a program to use the typedef keyword in structure to provide a new name to the struct and initialize the structure variables, as follow: Struct.c Output: Student Roll No: 30 Student name: Lockie Fergusion Student Subject: Mathematics Student Teacher Name: Jasmine In the above program, we use the typedef keyword to define a new name for the struct data type is Students and initialize the variables using it. defineA #define is the pre-processor used to represents the constant aliases for various data. It is used to define the constant variable for different data types in C. It is defined outside of the main program. Syntax In the above syntax, #define is a pre-processor that defines the token as a constant variable name, and the value represents the token value. After initializing the constant variable in the pre-processor, we can use the value using the variable in a program. Example 1: Consider a program to use the #define pre-processor in C. Define.c Output: Display the PI Constant value using the #define is: 3.14 Example 2: Consider a program to get the area of a circle in C using the #define pre-processor. Area.c Output: Enter the radius of the circle : 5 The area of the circle is: 78 In the above program, we use PI as a continuous variable using the #define pre-processor. And when the program is executed, the PI value automatically calls in a program. Example 3: Consider a program to demonstrate the importance of typedef over the #define for data types. Pgrm.c Output: Sizeof x:8 Sizeof y:8 Sizeof z:8 Sizeof p:8 Sizeof q:1 Sizeof r:1 Difference between the typedef and the #define in CFollowing are the differences of the typedef and the #define, as follows:
Next TopicBig O Notation in C |