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

typedef的语法

typedef <现有名称> <别名>

在上述语法中,'现有名称' 是已经存在的变量的名称,而 '别名' 是对已经存在的变量的另一个名称。

例如,假设我们想创建一个类型为 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 关键字减少了代码的长度和数据类型的复杂性。它还有助于理解程序。

让我们看另一个使用 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("\nName of the student is: %s", s1.name);
    printf("\nAge 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;

在上述语句中,p1p2 是类型为 'ptr' 的变量。

标签: c语言, c语言教程, c语言技术, c语言学习, c语言学习教程, c语言下载, c语言开发, c语言入门教程, c语言进阶教程, c语言高级教程, c语言面试题, c语言笔试题, c语言编程思想