A brief analysis of the usage of typeof keyword in C language

  • 2020-05-12 03:01:09
  • OfStack

preface

The typeof keyword in the C language is used to define variable data types. It is widely used in the linux kernel source code.

Here is an example of typeof in the Linux kernel source code:


#define min(x, y) ({        \
  typeof(x) _min1 = (x);     \
  typeof(y) _min2 = (y);     \
  (void) (&_min1 == &_min2);   \
  _min1 < _min2 ? _min1 : _min2; })

1. When the type of x is int, the data type of the _min1 variable is int.

2. When x is an expression (e.g. x = 3-4), the data type of the _min1 variable is the data type of the result of this expression.
.......

3.typeof parentheses can also be functions

Ex. :


 int function(int, int);
  typeof(function(1. 2)) val;

At this point, the data type of val is the data type of the return value of the function function(int, int), i.e., int. Note: typeof does not execute the function function.

The typeof keyword is somewhat similar to the decltype keyword in c++.


Related articles: