[转] gcc 扩展(1)

■ 匿名 unions

struct {

      char a;

      union {

          char c[4];

          int i;

      };

      char b;

} x;

x.c 和 x.i 是正确的。

■ 不定长数组

void combine(char *s1, char *s2)

{

      char s[strlen(s1) + strlen(s2) + 2];

      strcpy(s, s1);

      strcat(s, s2);

      puts(s);
}

■ zeor 数组

typedef struct {

      int len;

      char s[0];

} VL;

VL *vls = (VL *)malloc(sizeof(VL) + 100);

vls->s[0] = 'm';

vls->s[1] = 'i';

vls->s[2] = 'k';

vls->len = 3;

... ...

--------------------------------------------------

别一种形式为:

typdef struct {
     int len;

     char s[];

} VL;

static VL vls = { 3, {'m', 'i', 'k' }};

注意: vls 必须定义为 static 变量或全局变量

■ 复合结构返回值

gcc 扩展一个非常有用的技巧。

例子1:

int i = ( { int a = 10; int b; b = a + 1; } );

结果,i 的值为 11

例2:

#define even(x) (                        \

   { int y = x;                          \

     2 * (y / 2) == y ? y : y + 1;       \

   }                                     \

)

当以这种形式出现时,就能够正常工作了。

int a_even = even(i++);

■ 简化的条件表达式

条件表达式: x = y ? y : z;

简化为: x = y ? : z;

转自:http://blog.chinaunix.net/u/11773/showart_179990.html

posted @ 2010-11-24 15:16  napoleon_liu  阅读(252)  评论(0)    收藏  举报