【C语言_24】typedef关键词
发布时间:2023-02-17 13:27:15 224 相关标签:
1.typedef定义类型别名
定义int的别名int32_t:
2.typedef的使用
#include
int main()
{
typedef int int32_t;//作用域:{}里申请的,只能在{}里用
int32_t n=666;
printf("n=%d",n);
return 0;
}
运行结果:

#include
typedef int int32_t;//作用域:从声明开始直到该源文件结束
int32_t add(int32_t a,int32_t b)
{
return a+b;
}
int main()
{
int32_t a=111;
int32_t b=222;
int32_t sum=add(a,b);
printf("sum=%d",sum);
return 0;
}
运行结果:

3.typedef经常被使用于结构
#include
typedef struct{
char name[20];
int gender;
double height;
double weight;
}person;//person是这个结构类型的别名
int main()
{
person per={"李四",2,178.5,64.3};
printf("%s\t%d\t%.2lf\t%.2lf\t",
per.name,per.gender,per.height,per.weight);
return 0;
}
运行结果:

4.typedef与#define的区别:
1.#define可以给数值定义别名,typedef不行
2.#define由预处理器处理,并且修改替换代码。
3.typedef不受预处理影响,在编译时由编译器处理
4.虽然#define也能为类型定义别名,但某些情况下,使用typedef更合适
5.提高整型的可移植性
- 整型类型的别名无需自己定义
- 编译器会根据本平台的整型范围大小,设置对应的别名
- 添加头文件就可以使用

6.如何保证printf的可移植性呢?
int32_t n=666;
printf("n=%d",n);
//如果这个int32_t表示的是long,那就不应该是%d,而是%ld
如何避免这类错误呢?可以添加头文件

#include
#include
#include
int main()
{
int32_t n=666;
printf("n=%"PRId32"\n",n);
return 0;
}
运行结果:

持续更新【C语言】系列!有需要的请移步秃头程序媛主页!
文章来源: https://blog.51cto.com/u_15420562/5759139
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报