Reputation: 23
I'm trying to use the ternary operator (?:
) to initialize a character array to either one string or another
char answ[] = ans > 0 ? "Anton" : "Danik";
Where ans
is just an integer obtained earlier and I keep getting the error:
initialization with '{...}' expected for aggregate object
Is it that you simply can't initialize arrays through a ternary operator?
I also tried this:
char answ[] = { ans>0 ? "Anton" : "Danik" };
What gave the error:
value of type "const char *" cannot be used to initialize an entity of type "char"
Upvotes: 1
Views: 744
Reputation: 2884
Is it that you simply can't initialize arrays through a ternary operator?
Indeed, you can't.
In your example, you don't want to have just array. You want to have string literal - a specific array. Unfortunately, compiler doesn't treat answ
as one, because of you try to use conditional operator for initialization. Compiler treats it directly as array of char
s.
But there is different method of declaring C strings - using const
and pointer.
const char* answ = ans > 0 ? "Anton" : "Danik";
The downside of this approach is, well, const
- you cannot modify this string.
That's why, if you are using C++, you should use its strings - std::string
:
std::string answ = ans > 0 ? "Anton" : "Danik";
In C, you could do:
char answ[6];
ans > 0 ? strcpy(answ, "Anton") : strcpy(answ, "Danik");
But at this point, ternary operator is just less verbose than normal if-else, so don't do that.
Upvotes: 3