c - 定义新类型时需要你有一个别名来编译它?
问题描述
我从 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;
}
解决方案
不,你不必给typedef
一个结构起一个新名字,使用关键字struct
和所谓的“结构标签”就足够了。在示例中,标签是Course
如此没有typedef
类型将被调用struct Course
。
使用 atypedef
可以让您抽象出类型的确切细节,这可能有用但不是必需的,它只是语言的一个特性。
例如,您可以将其与任何类型一起使用
typedef unsigned short uint16_t;
如果您知道 a是特定编译器的正确大小,那么这将是一种创建 C99<stdint.h>
类型的方法,依此类推。uint16_t
short
线
Course course;
简单地定义一个名为course
type的变量Course
,即结构的一个实例。没有typedef
你会写
struct Course course;
推荐阅读
- python - 如何删除与python中的tagName和属性匹配的所有XML标签
- angular - Ionic 3 应用程序未编译
- android - 缓存和 Json 解析
- django - 无法使用套接字启动 gunicorn 服务
- javascript - 使用 React JS 在页面上渲染元素
- c# - 旋转父母,让孩子朝某个方向看
- mongodb - 为什么 mongo findById 不起作用但匹配 _id 是?
- typescript - 在页面之间导航时如何使菜单正确显示
- reactjs - React Hooks:即使状态没有改变也要重新渲染
- javascript - 如何为变量简化代码?