MAX使用gcc的typeof运算扩展 [英] MAX using typeof extension of gcc

查看:196
本文介绍了MAX使用gcc的typeof运算扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用C编程相当长的一段now.So我决定学一门位高级CI听说gcc编译器的extensions.Below我看到了一个code为MAX(),我直到现在已经实施如下:

 的#define MAX(X,Y)((X)>(Y)(X):?(Y))

这是新的定义,我found.Unfortunately我甚至无法理解下面code做了什么?我为什么会做如下而不是如上?

 的#define MAX(A,B)\\
    ({\\
    typeof运算(一)_a =(一); \\
    typeof运算(B)= _B(B); \\
    _a> _b? _a:_b; })


解决方案

的优点是,它避免了评估参数多次经典的宏。

通过引入局部变量(使用的typeof 来克隆的参数的类型),实际前pressions只计算一次,返回值是然后只需使用局部变量,而不是重新评估输入前pression,经典的宏有做的。

如果比较像这样调用会发生什么:

  INT A = 0,B = 1;
const int的C = MAX(++一,++ B);

在第一种情况下,因为输入的前pressions有副作用,结果将难以predict。在第二种情况下,所以一切的行为就好像参数只计算一次MAX()是一个普通的功能。

另外,你的第一个宏例如未能到处括在括号内的参数,这是危险的。

I have been programming in C for quite a while now.So I decided to learn a bit of advanced C.I heard of gcc compiler extensions.Below I saw a code for the MAX() that I till now has implemented as follows

#define MAX(x,y) ((x) > (y)? (x): (y))

This is the new definition that I found.Unfortunately I can't even understand what the below code does? and why would I do it as below instead of as above?

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

解决方案

The advantage is that it avoids evaluating the arguments as many times as the classic macro.

By introducing local variables (using typeof to "clone" the type of the arguments), the actual expressions are only evaluated once, the return value is then simply using the local variable rather than evaluating the input expression again, as the classic macro has to do.

Compare what happens if called like this:

int a = 0, b = 1;
const int c = MAX(++a, ++b);

In the first case, because the input expressions have side-effects, the result will be hard to predict. In the second case, the arguments are only evaluated once so everything behaves as if MAX() was a regular function.

Also, your first macro example is failing to enclose the arguments in parenthesis everywhere, which is dangerous.

这篇关于MAX使用gcc的typeof运算扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆