3

Reading the documentation of the ternary operator, I've realized that there are two special cases that I've never used:

  • you can use it with functions that return void : bool ? void : void
  • you can throw inside a ternary operator

So is the following valid, completely defined, and oftenly used (assuming that this is a class member, and the class owns a Type _data[Size]) ?

Type& at(const unsigned int i) 
{
    return (i < Size) ? (_data[i]) : (throw std::out_of_range("ERROR"));
}
Vincent
  • 57,703
  • 61
  • 205
  • 388
  • (also it may help you to know that this operator is known as the "conditional operator". It's only "ternary" in the same way that `+` is binary, etc.) – Dave Jul 20 '13 at 23:37
  • `throw` in a condition operator is often used in C++11 `constexpr` programming – Cubbi Jul 21 '13 at 17:52

1 Answers1

5

Your example is valid and well-defined (assuming suitable definitions of Size and _data). As to "oftenly used" - I personally have never seen such a construct before, for what it's worth.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • +1 Valid, well-defined, but pretty much never used. If you wanna throw, use a good old `if` for readability. It's just a style issue though, so YMMV. Just don't be surprised if everybody and their dog yells at you when they see this construct. – syam Jul 20 '13 at 23:53