Introduction: Computer language is the basis and specification for compiler and programmer to communicate. GNU C is a special function of GCC and widely used in Linux kernel.

Help: gcc.gnu.org/onlinedocs/…

 

The keyword typeof is used to get the data typeof the expression.

A simple example looks like Listing 1:

[cpp]  view plain copy

  1. char *chptr01;  
  2.   
  3. typeof (*chptr01) ch; // equivalent to char ch;
  4.   
  5. typeof (ch) *chptr02; Char *chptr02;
  6.   
  7. typeof (chptr01) chparray[5]; // equivalent to char *chparray[5];

In this example, the data type of CHpTR01 is char *, and that of *chptr01 is char.

A complex example, like Listing 2:

[cpp]  view plain copy

  1. #include <stdio.h>  
  2.   
  3. #define array(type, size) typeof(type [size])  
  4.   
  5. int func(int num)  
  6. {  
  7.     return num + 5;  
  8. }  
  9.   
  10. int main(void)  
  11. {  
  12. typeof (func) *pfunc = func; Int (*pfunc)(int) = func;
  13.     printf(“pfunc(10) = %d\n”, (*pfunc)(10));  
  14.   
  15. array(char, ) charray = “hello world!” ; Char charray[] = “Hello world!” ;
  16. typeof (char *) charptr = charray; Char *charptr = charray;
  17.   
  18.     printf(“%s\n”, charptr);  
  19.   
  20.     return 0;  
  21. }  

Example output:

[cpp]  view plain copy

  1. pfunc(10) = 15  
  2. hello world!  

If typeof’s operand is a data type, its result is that data type, as in line 16.

In the Linux kernel, as shown in Listing 3:

[cpp]  view plain copy

  1. / * Linux – 2.6.38.8 / include/Linux/kernel h * /
  2.   
  3. #define min(x, y) ({                \  
  4.     typeof(x) _min1 = (x);          \  
  5.     typeof(y) _min2 = (y);          \  
  6.     (void) (&_min1 == &_min2);      \  
  7.     _min1 < _min2 ? _min1 : _min2; })  
  8.   
  9. #define max(x, y) ({                \  
  10.     typeof(x) _max1 = (x);          \  
  11.     typeof(y) _max2 = (y);          \  
  12.     (void) (&_max1 == &_max2);      \  
  13.     _max1 > _max2 ? _max1 : _max2; })  

Get the data types of x and y from Typeof, then define two temporary variables and assign the values of x and y to these two temporary variables, and finally compare.

In addition, the (void)(&_min1 == &_min2) statement in the macro definition is used to warn that x and y cannot belong to different data types.