用三元算子初始化结构

时间:2013-07-27 10:27:31

标签: c struct initialization ternary-operator

为什么三元运算符不能用于初始化结构类型,而它可用于初始化基类型,如 int

示例代码:

#include <stdio.h>
#define ODD 1

int main(int argc, const char *argv[])
{
  static struct pair_str {
    int first; 
    int second; 
  } pair = ( ODD ) ?  {1,3} : {2,4}; // ERROR

  printf("pair %d %d\n", pair.first, pair.second); 

  int number = (ODD) ? 1 :2;  // FINE

  return 0;

}

编译器错误:

/home/giuseppe/struct.c: In function ‘main’:
/home/giuseppe/struct.c:12:23: error: expected expression before ‘{’ token
/home/giuseppe/struct.c:12:29: error: expected expression before ‘:’ token

1 个答案:

答案 0 :(得分:11)

当然,请使用C99复合文字:

pair = odd ? (struct pair_str){ 1, 3 } : (struct pair_str){ 2, 4 };