Difference between typedef and define in C
Categories: C 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
typedef data_type newName
or typedef <existing_name> <alias_name>
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
#include <stdio.h>
typedef int Length; // typedef provide the int data type to a new name as Length
int main()
{
Length num1, num2, sum; // here Length variable is treated as the int data type
printf(" Enter the first number:");
scanf(" %d", & num1);
printf(" Enter the second number:");
scanf(" %d", & num2);
sum = num1 + num2;
printf(" The sum of the two numbers is: %d", sum);
return 0;
}
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
#include <stdio.h>
#include <conio.h>
typedef unsigned char Bit;
int main()
{
Bit B1, B2;
B1 = 'D';
B2 = 'E';
printf( " Demonstrate the use of typedef Keyword ");
printf (" Print a single Byte: %c", B1);
printf (" Print a single Byte: %c", B2);
return 0;
}
Output:
Demonstrate the use of typedef Keyword
Print a single Byte: D
Print a single Byte: E