C语言typedef关键字基础教程文档

收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體

typedef 是C编程中使用的关键字,用于为C程序。当我们为命令定义别名时,它的行为类似。简而言之,我们可以说这个关键字用于重新定义一个已经存在的变量的名称。

typedef的语法

typedef <existing_name> <alias_name>
在以上语法中," existing_name" 是已经存在的变量的名称,而" alias name" 是给该变量提供的另一个名称。
例如,假设我们要创建一个类型为 unsigned int 的变量,那么如果我们要声明此类型的多个变量,那么它将变得很繁琐。为了解决该问题,我们使用 typedef 关键字。
typedef unsigned int unit;
在上面的语句中,我们已经使用 typedef 关键字声明了类型为unsigned int的 unit 变量。
现在,我们可以通过编写以下语句,创建类型为 unsigned int 的变量:
unit a, b; 
代替编写:
unsigned int a, b;
到目前为止,我们已经观察到 typedef 关键字为现有变量提供了备用名称,从而提供了一个很好的快捷方式。当我们处理长数据类型,尤其是结构声明时,此关键字很有用。
让我们通过一个简单的例子来理解。
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
输出
Value of i is :10 
Value of j is :20 

将typedef与结构一起使用

请考虑以下结构声明:
struct student
{
char name[20];
int age;
};
struct student s1; 
在上面的结构声明中,我们通过编写以下语句创建了 student 类型的变量:
struct student s1;
上面的语句显示了变量s1的创建,但是该语句相当大。为了避免这么大的声明,我们使用 typedef 关键字创建 student 类型的变量。
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2; 
在上面的语句中,我们已声明了struct student类型的变量 stud 。现在,我们可以在程序中使用 stud 变量来创建 struct student 类型的变量。
上面的typedef可以写成为:
typedef struct student
{
char name[20];
int age; 
} stud;
stud s1,s2;
根据上述声明,我们得出结论, typedef 关键字减少了代码的长度和数据类型的复杂性。
让我们看看另一个示例,其中键入了结构声明的定义。
#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}
输出
Enter the details of student s1: 
Enter the name of the student: Peter 
Enter the age of student: 28 
Name of the student is : Peter 
Age of the student is : 28 

使用带指针的typedef

我们还可以借助 typedef 为指针变量提供另一个名称或别名。
例如,我们通常声明一个指针,如下所示:
int* ptr;
我们可以如下重命名上述指针变量:
typedef int* ptr;
在上面的语句中,我们声明了类型为 int * 的变量。现在,我们可以简单地使用' ptr'变量来创建 int * 类型的变量,如以下语句所示:
ptr p1, p2 ;
在上面的语句中, p1 和 p2 是' ptr'类型的变量。