typeof

typeof 是 C 语言的一个扩展,用于获取表达式的类型。它的主要用途包括:

1、声明变量类型:

可以用 typeof 来声明变量,而无需显式指定变量的类型。这样可以使代码更加简洁和易读,特别是在处理复杂的表达式时。

2、简化类型名称:

在定义结构体、联合体等复杂类型时,使用 typeof 可以简化类型名称的书写,提高代码的可维护性和可读性。

3、简化宏定义:

在宏定义中,typeof 可以帮助获取宏参数的类型,从而使宏更加通用和灵活。
 
typeof的举例demo:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct apple {
    int weight;
    int color;
};

struct apple *create_apple(int weight, int color) {
    struct apple *a = malloc(sizeof(struct apple));
    if (a == NULL) {
        printf("Memory allocation error.\n");
        return NULL;
    }

    a->weight = weight;
    a->color = color;

    return a;
}

int main() {
    typeof(create_apple(0, 0)) a1 = create_apple(150, 1);
    typeof(create_apple(0, 0)) a2 = create_apple(120, 2);

    printf("Apple 1 - Weight: %d, Color: %d\n", a1->weight, a1->color);
    printf("Apple 2 - Weight: %d, Color: %d\n", a2->weight, a2->color);

    free(a1);
    free(a2);

    return 0;
}
 
执行结果如下:
0
 
 
 
 
 
posted @ 2024-04-04 09:13  lethe1203  阅读(13)  评论(0编辑  收藏  举报