linux中的typeof使用

43 篇文章 0 订阅
14 篇文章 2 订阅
Another way to refer to the type of an expression is with typeof. The syntax of using of this keyword looks like sizeof, but theconstruct acts semantically like a type name defined with typedef.

There are two ways of writing the argument to typeof: with anexpression or with a type. Here is an example with an expression:

     typeof (x[0](1))

This assumes that x is an array of pointers to functions;the type described is that of the values of the functions.

Here is an example with a typename as the argument:

     typeof (int *)

Here the type described is that of pointers to int.

If you are writing a header file that must work when included in ISO Cprograms, write __typeof__ instead of typeof.

A typeof construct can be used anywhere a typedef name can beused. For example, you can use it in a declaration, in a cast, or insideof sizeof or typeof.

The operand of typeof is evaluated for its side effects if andonly if it is an expression of variably modified type or the name ofsuch a type.

typeof is often useful in conjunction withstatement expressions (see Statement Exprs). Here is how the two together canbe used to define a safe “maximum” macro which operates on anyarithmetic type and evaluates each of its arguments exactly once:

     #define max(a,b) \
       ({ typeof (a) _a = (a); \
           typeof (b) _b = (b); \
         _a > _b ? _a : _b; })

The reason for using names that start with underscores for the localvariables is to avoid conflicts with variable names that occur within theexpressions that are substituted for a and b. Eventually wehope to design a new form of declaration syntax that allows you to declarevariables whose scopes start only after their initializers; this will be amore reliable way to prevent such conflicts.

Some more examples of the use of typeof:

  • This declares y with the type of what x points to.
              typeof (*x) y;
    
  • This declares y as an array of such values.
              typeof (*x) y[4];
    
  • This declares y as an array of pointers to characters:
              typeof (typeof (char *)[4]) y;
    

    It is equivalent to the following traditional C declaration:

              char *y[4];
    

    To see the meaning of the declaration using typeof, and why itmight be a useful way to write, rewrite it with these macros:

              #define pointer(T)  typeof(T *)
              #define array(T, N) typeof(T [N])
    

    Now the declaration can be rewritten this way:

              array (pointer (char), 4) y;
    

    Thus, array (pointer (char), 4) is the type of arrays of 4pointers to char.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值