C typedef的代码实例

Typedef 的基本语法

typedef 的基本语法格式如下:

typedef existing_type new_type_name;

existing_type 是已经存在的数据类型,new_type_name 是为该类型定义的新名称。

示例:

typedef unsigned int uint;
uint a = 10;  // 等同于 unsigned int a = 10;

为基本类型创建别名

typedef 常用于为基本数据类型创建更简洁或更有意义的别名。

typedef char byte;
typedef int bool;
typedef float real;

byte b = 'A';
bool flag = 1;
real pi = 3.14159;

为结构体创建别名

typedef 可以简化结构体的声明和使用。

// 未使用typedef
struct Point {
    int x;
    int y;
};
struct Point p1;

// 使用typedef
typedef struct {
    int x;
    int y;
} Point;
Point p2;

为指针类型创建别名

typedef 可以简化指针类型的声明。

typedef char* String;
String s = "Hello";

typedef int* IntPtr;
IntPtr p = (int*)malloc(sizeof(int)*10);

为函数指针创建别名

typedef 特别适合简化复杂的函数指针声明。

typedef int (*CompareFunc)(const void*, const void*);

int compare_ints(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

CompareFunc cmp = compare_ints;
int arr[] = {5, 2, 8, 1};
qsort(arr, 4, sizeof(int), cmp);

为数组类型创建别名

typedef 可以为数组类型创建别名,特别是多维数组。

typedef int Vector3[3];
typedef float Matrix4x4[4][4];

Vector3 v = {1, 2, 3};
Matrix4x4 m = {
    {1.0f, 0.0f, 0.0f, 0.0f},
    {0.0f, 1.0f, 0.0f, 0.0f},
    {0.0f, 0.0f, 1.0f, 0.0f},
    {0.0f, 0.0f, 0.0f, 1.0f}
};

为复杂类型创建多层别名

typedef 可以嵌套使用,为复杂类型创建多层别名。

typedef int* IntPtr;
typedef IntPtr* IntPtrPtr;

int x = 10;
IntPtr p = &x;
IntPtrPtr pp = &p;

平台无关的类型定义

typedef 常用于创建平台无关的类型定义,提高代码可移植性。

#ifdef _WIN32
    typedef __int64 int64_t;
#else
    typedef long long int64_t;
#endif

int64_t big_num = 9223372036854775807LL;

类型安全

typedef 可以增强类型安全性,防止误用。

typedef int Meters;
typedef int Kilograms;

Meters length = 10;
Kilograms weight = 70;

// length = weight;  // 虽然语法允许,但逻辑错误明显

与宏定义的区别

typedef 与 #define 有重要区别:typedef 是类型定义,#define 是文本替换。

#define PINT int*
typedef int* intPtr;

PINT a, b;     // a是int*,b是int
intPtr c, d;   // c和d都是int*

在C++中的使用

在C++中,typedef 可以用 using 替代,但 typedef 仍然被广泛支持。

typedef std::vector<std::string> StringVector;

// C++11 equivalent
using StringVector = std::vector<std::string>;

实际应用案例

以下是一个综合应用示例,展示typedef在实际项目中的使用:

typedef struct {
    int id;
    char name[50];
} Employee;

typedef Employee* EmployeePtr;

typedef void (*PrintFunc)(EmployeePtr);

void printEmployee(EmployeePtr emp) {
    printf("ID: %d, Name: %s\n", emp->id, emp->name);
}

int main() {
    Employee e = {101, "John Doe"};
    EmployeePtr ep = &e;
    PrintFunc pf = printEmployee;
    pf(ep);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值