首页 > 解决方案 > 定义新类型时需要你有一个别名来编译它?

问题描述

我从 Edubaca 得到这个代码

在第 12 行,Edubaca 描述了Course取别名course,这是什么原因以及为什么这样的语法?另外,第 4 行的课程是否必要?

我试过的:

- 删除第 13
Course- 将第 4 行和第 9 行更改为course

#include <stdio.h>//Add all the basic C language libraries
#include <string.h>//Add the String library to perform string actions
//typedef for give struct keyword to user wanted keyword as like below (Courses)
typedef struct Course {
    char courseName[60];//declare character variable
    float CourseFee;//declare float variable
    char companyName[100];//declare character variable
    int loginID;//declare integer variable
} Course; //To make work user defined keyword we have call the keyword from here
//main method to execute application code
int main( ) {
    //Taken Courses name as course( alias name)
    Course course;
    //Copying character values into varaible
    strcpy(course.courseName, "C Programming");
    strcpy(course.companyName, "EDUCBA");
    //Initailize float values into varaible
    course.CourseFee = 5000.00;
    //Initailize integer values into varaible
    course.loginID=2452;
    //display the output of all the declared variable below
    printf( "Course Name : %s\n", course.courseName);
    printf( "Company Name : %s\n", course.companyName);
    printf( "Course Fee : %f\n", course.CourseFee);
    printf( "Login ID : %d\n", course.loginID);
    return 0;
}

标签: ctypedef

解决方案


不,你不必给typedef一个结构起一个新名字,使用关键字struct和所谓的“结构标签”就足够了。在示例中,标签是Course如此没有typedef类型将被调用struct Course

使用 atypedef可以让您抽象出类型的确切细节,这可能有用但不是必需的,它只是语言的一个特性。

例如,您可以将其与任何类型一起使用

typedef unsigned short uint16_t;

如果您知道 a是特定编译器的正确大小,那么这将是一种创建 C99<stdint.h>类型的方法,依此类推。uint16_tshort

线

Course course;

简单地定义一个名为coursetype的变量Course,即结构的一个实例。没有typedef你会写

struct Course course;

推荐阅读