Pipsydoodles
Pipsydoodles

Reputation: 37

Uunderstand the limits of the ? operator

if say I had a function that would ultimately come true could I do something like this?

somefunction(data) ? cout << "This is true" << endl : cout << this false << endl; 

or am I little off? or is this impossible with such said operand? or could I call a different function? Ultimately, I a trying to figure out the limitations of this functions and other uses that aren't apparent in the c++ tutorial site.

std::cout<< (somefunction(data) ? "This is true" : anotherfunction (data) <

or other cases that people can think of...

Upvotes: 0

Views: 167

Answers (3)

Mats Petersson
Mats Petersson

Reputation: 129374

Not quite an "answer", but bear in mind that nearly always, using ternary operators for anything beyond the most simple things is "bad".

Reasonable usage is something like:

cout << "There are " << count << " item" << ((count != 1) ? "s":"") 
     << " in your basket";

But if your ternary operators are nested, then you want to use if/else type constructs instead. People will want to read the the code without pulling their hair out in the future!

Of course, the initial statement can be done without ternary operators, assuming the result is a bool [and if it isn't, you could make it to a bool with a static_cast<bool>(someFunction(data))].

cout << "This is " << boolalpha << someFunction(data) << endl;

Upvotes: 1

Adrian Ratnapala
Adrian Ratnapala

Reputation: 5693

The "limitation" is that the three arguments have to be expressions, and there are rules about their types. In your case, that all works out since cout << foo is an expression. Although you need to replace this false with "this is false".

But as others have pointed out, it is better to use the bare strings as your expressions. I might have written

std::cout << "This is " << (somefunction(data) ? "true" : "false") << ".\n";

Upvotes: 0

Liam McInroy
Liam McInroy

Reputation: 4366

I would look at Wikipedia. Basically it's syntax is

condition ? trueOutput : falseOutput;

Also you can nest them. You can output any value, but the condition has to be a boolean.

So in your case it would be:

cout << (someFunction(data) ? "True" : "False") << endl;

You can then nest this even!

cout << (someFunction(data) ? "True" : (newTernary(data) ? "False, but true" : (finalTernary(data) ? "False, false, and finally true" : "Always false:("))) << endl;

Upvotes: 1

Related Questions