typedef 是C编程中使用的关键字,用于为C语言中已经存在的变量提供一些有意义的名称。当我们为命令定义别名时,它的行为类似。简而言之,我们可以说此关键字用于重新定义已经存在的变量的名称。
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
考虑以下结构声明:
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: Learnfk Enter the age of student: 28 Name of the student is : Learnfk Age of the student is : 28
我们还可以借助 typedef 为指针变量提供另一个名称或别名。
例如,我们通常声明一个指针,如下所示:
int* ptr;
我们可以重命名上述指针变量,如下所示:
typedef int* ptr;
在上面的语句中,我们声明了类型为 int * 的变量。现在,我们只需使用' ptr'变量即可创建 int * 类型的变量,如以下语句所示:
ptr p1, p2 ;
在上面的语句中, p1 和 p2 是类型" ptr" 的变量。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)