结构的初始化与三元运算符 [英] Initialization of structure with ternary operator
本文介绍了结构的初始化与三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么三元运算符不能用来初始化结构类型,而它可以被用来初始化一个基本类型一样的 INT 的?
举例code:
的#include<&stdio.h中GT;
#定义ODD 1INT主(INT ARGC,为const char * argv的[])
{
静态结构pair_str {
诠释第一;
诠释秒;
}对=(ODD)? {1,3}:{2,4}; //错误 的printf(对%D \\ n,pair.first,pair.second); INT数=(ODD)? 1:2; // FINE 返回0;
}
编译器错误:
/home/giuseppe/struct.c:在函数'主':
/home/giuseppe/struct.c:12:23:错误:预期前$之前'{'令牌p $ pssion
/home/giuseppe/struct.c:12:29:错误:之前的预期前pression':'令牌
解决方案
当然,利用C99复合文字:
对奇=? (结构pair_str){1,3}:(结构pair_str){2,4};
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
解决方案
Sure, use C99 compound literals:
pair = odd ? (struct pair_str){ 1, 3 } : (struct pair_str){ 2, 4 };
这篇关于结构的初始化与三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文