Initialization of structure with ternary operator

若如初见. 提交于 2019-12-06 06:20:05

问题


Why the ternary operator cannot be used to initialize a structure type, while it can be used to initialize a base type like int?

Example code :

#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;

}

Compiler errors :

/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:


Sure, use C99 compound literals:

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


来源:https://stackoverflow.com/questions/17896743/initialization-of-structure-with-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!