C is such a dominant language of its time, and so far, you can even give your chosen names to those primary data types and create your own named data type by combining the data type and its qualifiers.
The typedef
keyword in C
typedef
is a C keyword implemented to tell the compiler to assign alternative names to C's pre-existing data types. This keyword, typedef,
is typically used with user-defined data types if the names of the datatypes become a bit convoluted or complicated for the programmer to obtain or use within the program. The general format for implementing the typedef
keyword is:
Syntax:
typedef <existing_names_of_datatype> <alias__userGiven_name>;
Here's a sample code snippet of how typedef
work in C:
Example:
typedef signed long slong;
The above statement defines a signed qualified "slong" data type. This "slong" is a user-defined identifier that can be implemented in the C program to define any signed long variable type.
Example:
slong g, d;
The above code creates two variables named 'g
' and 'd
', which will be of type signed long, and this quality of signed long is getting detected from the "slong
" (typedef), which already defined the meaning of the "slong
" in the program.
Various Applications of typedef
The concept of typedef
can be applied to define a user-defined data type with a specific name and type. You can also use this typedef
with structures. Here's what it looks like:
Syntax:
typedef struct
{
type first_member;
type sec_member;
type thrid_member;
} nameOfType;
In the above code, "nameOfType" matches the definition of the structure associated with it. Now, you can apply this unique name to declare a variable of this struct type.
Example:
nameOfType type1, type2;
Program to display structure in C using typedef
:
Example:
#include<stdio.h>
#include<string.h>
typedef struct professor
{
char p_name[50];
int p_sal;
} prof;
void main(void)
{
prof pf;
printf("\n Enter Professor details: \n \n");
printf("\n Enter Professor name:\t");
scanf("% s", pf.p_name);
printf("\n Enter professor salary: \t");
scanf("% d", &pf.p_sal);
printf("\n Input done ! ");
}
Using typedef
with Pointers
The typedef
can also be implemented for providing a pseudo name to pointer variables. In this below-mentioned code snippet, you have to use the typedef
, as it is advantageous for declaring pointers.
Example:
int* a;
Here the binding of the pointer (*
) is done on the right side. With a statement declaration like this, you declare it as a pointer of type int
(integer).
Example:
typedef int* pntr;
pntr g, h, i;