typeof keywords C language

c language typeof keywords, the C language in a new extension. typeof parameters can be in two forms: an expression or type .

Following two equivalent statement is used to declare a variable int get class

typeof(int) a;
typeof('b') a; //相当于获取'b'的类型,定义一个变量a
// GCC中这个表达式的类型是int(自动提升为int),
// 注意typeof(char)和typeof('b')得到的不是一样的,这个用sizeof可以看出来

And declare an array of pointers to the following

typeof(int*) p1,p2;
// 等价于
int *p1,*p2;

typeof(p1) p2 //p1与p2的类型一致

typeof(int [10]) a1,a2;
int a1[10],a2[10];

typeof(typeof(char *)[4]) y;
// 这与下面的定义等价:
char *y[4];

// 注意
typeof(int *) p1,p2; // 定义两个指针p1和p2
int *p1, *p2;
typeof(int) *p3,p4;// 定义指针变量p3和int类型的变量p4
int *p3, p4;

If typeof for expression , the expression does not occur, will only get the type of expression , the following example declares a variable of type int var, because the expression foo () is of type int, because the expression does not is executed, so do not call foo () function

extern int foo();
typeof(foo()) var; //相当于等同去int var;

Under normal circumstances with typeof on it, but if you want to ISO C compatible, it is best to use in the form of double-underlined: typeof .

typeofAnd the typedeflike, in fact, can be used as long as typedefthe place can be used typeof.

Without limiting the use typeof

typeof structure type name:

  • Storage class specifier can not contain such externor static.

  • But allows the inclusion type qualifier, such as constor volatile.

For example, the following code is invalid because it in an extern statement typeof configuration.;

typeof(extern int) a;

The following code uses to declare external link identifier b is valid, an object that represents a type of int. The next statement is valid which states the use of a pointer const char type qualifiers, p represents a pointer can not be modified.

extern typeof(int) b;
typeof(char* const) p;//常指针,不能修改指针指向;

Use the macro statement typeof

Typeof main application is constructed in a macro definition. You can use typeof keyword to refer to the type of macro parameters.

#define pointer(T) typeof(T *)
#define array(T,N) typeof(T [N])
array (pointer(char),4) y;

// 下面是一个交换两个变量的值的宏定义:
#define SWAP(a,b) {\
      typeof(a) _t=a;\
      a=b;\
      b=_t;}
// 这个宏可以交换所有基本数据类型的变量(整数,字符,结构等)

Reference material

c language typeof keywords
in C language typeof keywords

Released five original articles · won praise 0 · Views 60

Guess you like

Origin blog.csdn.net/taokexia/article/details/105334017