前言
typeof() 是GUN C提供的一种特性,可参考C-Extensions,它可以取得变量的类型,或者表达式的类型。
本文总结了typeof()关键字的常见用法,并给出了相应的例子,以加深理解 。
typeof()关键字常见用法
typeof()关键字常见用法一共有以下几种。
- 不用知道函数返回什么类型,可以使用typeof()定义一个用于接收该函数返回值的变量
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct apple{
int weight;
int color;
};
struct apple *get_apple_info()
{
struct apple *a1;
a1 = malloc(sizeof(struct apple));
if(a1 == NULL)
{
printf("malloc error.\n");
return;
}
a1->weight = 2;
a1->color = 1;
return a1;
}
int main(int argc, char *argv[])
{
typeof(get_apple_info()) r1;//定义一个变量r1,用于接收函数get_apple_info()返回的值,由于该函数返回的类型是:struct apple *,所以变量r1也是该类型。注意,函数不会执行。
r1 = get_apple_info();
printf("apple weight:%d\n", r1->weight);
printf("apple color:%d\n", r1->color);
return 0;
}
- 在宏定义中动态获取相关结构体成员的类型
如下代码,定义一个和变量x相同类型的临时变量_max1,定义一个和变量y相同类型的临时变量_max2,再判断两者类型是否一致,不一致给出一个警告,最后比较两者。
#define max(x, y) ({ \
typeof(x) _max1 = (x); \
typeof(y) _max2 = (y); \
(void) (&_max1 == &_max2); \//如果调用者传参时,两者类型不一致,在编译时就会发出警告。
_max1 > _max2 ? _max1 : _max2; })