C语言typeof关键字如何正确使用?
- 内容介绍
- 文章标签
- 相关推荐
本文共计193个文字,预计阅读时间需要1分钟。
前言:C语言中,typeof关键字是用来定义变量数据类型的。在Linux内核源代码中广泛使用。下面是一个关于typeof的实例:
ctypedef struct { int a; char b;} MyStruct;
typedef struct { int a; char b;} AnotherStruct;
int main() { MyStruct ms; AnotherStruct as;
typeof(ms) msType; typeof(as) asType;
return 0;}
前言
C语言中 typeof 关键字是用来定义变量数据类型的。在linux内核源代码中广泛使用。
下面是Linux内核源代码中一个关于typeof实例:
#define min(x, y) ({ \ typeof(x) _min1 = (x); \ typeof(y) _min2 = (y); \ (void) (&_min1 == &_min2); \ _min1 < _min2 ? _min1 : _min2; })
1.当x的类型为是 int 时 _min1变量的数据类型则为 int。
2.当x为一个表达式时(例: x = 3-4), _min1变量的数据类型为这个表达式结果的数据类型。
.......
3.typeof括号中也可以是函数
例:
int function(int, int); typeof(function(1. 2)) val;
此时val的数据类型为 函数function(int, int)返回值的数据类型 ,即int类型。(注意: typeof并不会执行函数function)。
typeof关键字有点类似与c++中的decltype关键字。
本文共计193个文字,预计阅读时间需要1分钟。
前言:C语言中,typeof关键字是用来定义变量数据类型的。在Linux内核源代码中广泛使用。下面是一个关于typeof的实例:
ctypedef struct { int a; char b;} MyStruct;
typedef struct { int a; char b;} AnotherStruct;
int main() { MyStruct ms; AnotherStruct as;
typeof(ms) msType; typeof(as) asType;
return 0;}
前言
C语言中 typeof 关键字是用来定义变量数据类型的。在linux内核源代码中广泛使用。
下面是Linux内核源代码中一个关于typeof实例:
#define min(x, y) ({ \ typeof(x) _min1 = (x); \ typeof(y) _min2 = (y); \ (void) (&_min1 == &_min2); \ _min1 < _min2 ? _min1 : _min2; })
1.当x的类型为是 int 时 _min1变量的数据类型则为 int。
2.当x为一个表达式时(例: x = 3-4), _min1变量的数据类型为这个表达式结果的数据类型。
.......
3.typeof括号中也可以是函数
例:
int function(int, int); typeof(function(1. 2)) val;
此时val的数据类型为 函数function(int, int)返回值的数据类型 ,即int类型。(注意: typeof并不会执行函数function)。
typeof关键字有点类似与c++中的decltype关键字。

