views:

643

answers:

9
+6  A: 

ternary statements

chrissr
thank you, will accept this in 12 minutes when it lets me :)
Marcin
@Marcin - Technically, SLaks is correct. It's the Conditional Operator. A Ternary operator just refers to the number of parts. There could be other Ternary operators that differ from this example. http://msdn.microsoft.com/en-us/library/e4213hs1.aspx
Justin Niessner
I don't understand the downvotes. While this may not be the most precise answer, it's a correct answer nonetheless.
chrissr
The question shows a single statement with one single node (one conditional expression).
Johannes Schaub - litb
@marcin: except SLacks is more accurate and you should understand John Rasch's answer as to why the example is bad.
msw
Yes, but his question was "What are these kind of statements called". While his example alone was a single statement, his question asked what multiples of them are called.
chrissr
@chrissr: don't take the downvotes personally. SLack's answer should be preferred and some readers/voters may be attempting to make it bubble up. I didn't downvote.
msw
I knew what it did, I knew that it was a conditional statement. What I didn't know whats what those kinds were called. Thanks to chrissr, I now know that they are called ternary statements. This is the answer I was looking for.
Marcin
@Marcin, they're not called ternary statements any more than `testNumber > 1` is called a binary statement. Ternary is a description of how `?:` operates syntactically (it takes three parameters). The name of the operator is the "conditional operator", which is different in meaning from "a conditional statement". "Condition operator" is a name on the same level as "less than operator" for `<` and "subtraction operator" for `-` or "dereference operator" for `*`.
Eclipse
Well, there's no such thing as "ternary statement" in C++. This is a ternary *conditional operator*, which is a part of an *expression*, which is in turn making up an *expression statement*.
AndreyT
People will understand you, when you say "ternary operator", but only because there is only one of them in C++ (and most other languages).
Eclipse
If someone says "ternary statement" i immediately think of for loops
Johannes Schaub - litb
I'll have to remember the level of pedantry and think twice before responding to a c++ question again.
chrissr
@Justin: What other ternary operators does C++ have? The conditional operator is *the* ternary operator. (This answer, however, is wrong, that code in the question is called "nonsense".)
Roger Pate
+47  A: 

That's the conditional operator.

The expression a ? b : c evaluates to b if a is true and c if a is false.

In most languages, this is the only example of a ternary operator, an operator that takes three arguments.

SLaks
+1 I get fed up of people calling it the ternary operator. "Ternary" just refers to "three parts" in this case, there could be any number of such operators depending on the language! The one we are referring to here is the *conditional* (ternary) operator.
Noldorin
In theory, perhaps! In practice, there's only one ternary operator, so it's not really ambiguous.
Jan Gorzny
@Noldorin - Someday people will figure it out.
Justin Niessner
@Jan Gorzny: Why not use the correct term though? It's no more complicated. I'm sure there are languages out there with other "ternary" operators. Calling the operator ternary is like calling addition the "binary operator" - it's only part of the story.
Noldorin
@Naysayers Technically "conditional operator" is incorrect for the same reason. Any operator which branches based on a condition is a "conditional operator." That we associate this operator with that term is for the same reason we associate it with "ternary operator." Both are ambiguous, however there are usually no other ternary operators in the language, where there are multiple conditional operators.
jMerliN
Sure, but one is a lot less ambiguous than the other. And more descriptive, of course. You could go on a long time being incredibly precise over what the operator is termed, but I feel "conditional (ternary) operator" is the right compromise. :)
Noldorin
@jMerlin the C++ standard calls the operator "conditional operator".
Johannes Schaub - litb
@Johannes I wouldn't religiously go by what the ISO calls things. They clearly forgot about **if**, **while**, and **for** when they called that the "conditional operator." There are other oversight errors as well. In general, both are ambiguous terms. I'd prefer something like ternary-if or some legitimate and clear name.
jMerliN
@jMerliN: if, while, and for are not operators!
Thomas Padron-McCarthy
@Noldorin, for another ternary operator, off the top of my head, there's SQL with `x BETWEEN a AND b`
Eclipse
@Eclipse: Ah, good example. Didn't have the time to search any up, but that helps prove the point!
Noldorin
@jMerliN: Not going by the standard is a good idea when talking about the language?
GMan
I'd rather say "ternary" when talking about it then repeat "conditional <air-parenthesis> ternary </air-parenthesis> operator". I really doubt anyone would confuse that with the SQL 'between' clause.
Kelly French
@GMan: The standard is great for talking about the language spec and closely related issues, but not too much else. It's quoted too often, usually to beginners, when another answer would be better. (An easy trap to fall into, I'm guilty of this too, though I try to watch it.)
Roger Pate
+4  A: 

Ternary operator. http://en.wikipedia.org/wiki/Ternary_operation

jMerliN
+1  A: 

It's an expression with a ternary (or conditional) operator in it.

Jan Gorzny
Heh, I like the pedantry! You're absolutely right of course, the code only represents the expression, not the operator itself. (Still, I wouldn't normally pick over that.)
Noldorin
Your answer, as it is phrased at this moment, suggests that the words "ternary" and "conditional" are equivalent. However, that is not correct. They denote different things: **ternary** describes the *form* (the expression has three operands), **conditional** describes its *meaning* (it evaluates to either of two values according to a Boolean condition).
stakx
@stakx, I agree--ternary and conditional are not equivalent and I fully understand your comment. However, as other posts in this thread clearly show, they are equivalent in an informal sense: whichever word you use, with sufficient probability, your audience will understand it--if only because those who prefer 'conditional' get annoyed when people say 'ternary'. The only notable exception I see to this rule is the additional SQL operator. Note however that the question is tagged c++, so this example doesn't really apply if we restrict ourselves to this scope.
Jan Gorzny
I see what you mean. Fair enough. (Btw., I wasn't the one downvoting your answer, I just felt the urgent need to be pedantic and point out the difference. :-) -- You've made me curious about _"the additional SQL operator"_. Are you referring to `BETWEEN`?
stakx
Yeah, that's the one. Someone listed it in a comment to another post. (I should have said "the addtional SQL operator given in a prior comment" or something similar to be clearer--but there are character limits on comments)
Jan Gorzny
+2  A: 

On Language Syntax

What are these kind of statements in c++ called:

You've asked a question with multiple answers. Technically it would depend on the actual language used but what you've shown is very typical to a large number of languages that have a common syntax.

Statements

Statements are just a way of indicating a block of tokens that can be thought of as a single unit. Statements typically end with a semi-colon ";". Some statements are simple like

print 0;

which has one keyword and one literal, while others are more complex like

a = foo(c*10) + 5;  

which has an assignment encompassed by a return sub-expression and an arithmetic sub-expression, a function call with an argument resolution involving a multiplication sub-expression with a variable lookup as one of the operands.

Your statement is the results of an expression.

testNumber  >  1  ?  true  :  false       ;
====================================      ======================  
expression that needs evaluated           end-of-statement marker  

Conditional Operator

The conditional operator is sometimes referred to as the 'Ternary Operator'. It has an operator and three (hence ternary) operands.

testNumber > 1     ?    true     :    false   
==============    ---   =====   ---   ======
      |            |      |      |      |
      |            |    Exp2     |     Exp3
      |            |             |      
      |            └   Operator  ┘ 
      |
Exp1 (which has to be a boolean expression)

The results of either Exp1 or Exp2 is returned as the value of the conditional operator expression, Exp1 if "Condition" is true, Exp2 otherwise.

Explanation

The Conditional (ternary) Operator may not be as familiar to coders for various reasons.

One of its typical uses is to simplify code when we want to return different things based on some condition.

For example, given

a = 0;
b = 5;

we can easily return a division result in one line

return (a == 0) ? NaN : b/a;  //Not-A-Number

We could just build the return with the expression

return (b/a);

but we want to guard against division by zero. Using an if/else block would be code bloat.

if ( a == 0)
{
  return NaN;
}
else
{
  return b/a;
}

Related questions

http://stackoverflow.com/questions/160218/to-ternary-or-not-to-ternary
http://stackoverflow.com/questions/243217/which-coding-style-you-use-for-ternary-operator
http://stackoverflow.com/questions/522919/is-this-a-reasonable-use-of-the-ternary-operator

Kelly French
+1 for length...
SLaks
-1 for length. (I didn't really downvote, but I wouldn't upvote: there's too much information here to be useful, linking to relevant resources would do the OP a better service.)
Roger Pate
This answer isn't only long, but it's also wrong and confusing (what's a "return subexpression"?). It's not parsed that way at all.
Johannes Schaub - litb
@Johannes: In "a = foo(c * 10) + 5;" The return subexpression is the return value from the function call "foo(c * 10)". I didn't want to get into the different types of grammars, i.e. LL(1), LALR(1), LSR, or LR. All that is covered in a compiler class, which not everyone has taken.
Kelly French
@Kelly i think you have misunderstood me (my comment isn't particularly clear either, though). I'm not talking about parsing techniques. But how your answer, that the expression is parsed as `(testNumber) > (1 ? true : false)`, is wrong. See the other answers for how the precedence is.
Johannes Schaub - litb
@Johannes: Good catch, I goofed. I fixed the post to show the correct precedence and removed the parse tree section for good measure.
Kelly French
+17  A: 

Conditional Expression

      Conditional Expression
   <------------------------>
    (x < y)    ?      x : y
    |_____|    |________|
     Test       Conditional
    Expression   Operator

The '?' and ':' make up the conditional operator.

Dave18
+1 liking it. The only one so far that differs between the expression and the operator used.
Johannes Schaub - litb
+1 for the ASCII art from me. I love ASCII art. :)
stakx
+3  A: 

(As an annoying nitpicker: For some reason, despite the fact that the question is about the statement, most people give answers about the operator.)

Firstly, what you have in your example is indeed a statement. It is called an expression statement. There are different kinds of statements in C++ (declaration statement, jump statement, iteration statement etc.), and this one happens to be an expression statement. So, if your question is indeed about what kind of statement that is, the pedantically correct answer would be: it is an expression statement. End of story.

Now, secondly, if you want to go deeper, you might want to pick apart the expression that is used in this expression statement. The expression in this case has a conditional ?: operator at the top level. The first operand to that operator is a sub-expression using a relational > operator... and so on.

AndreyT
I think it's valid to interpret the question as asking about the conditional operator. If someone asks "what kind of program is this?" you don't answer "oh, it's a set of .cpp files. end of story". Like here, they look through the statement into the expression, although most, i suspect, just do it implicitly. Even if the questioner said "expression", you can likewise be pedantic and say "it's an expression. end of story" (it goes down to assignment-expression then, after which comes conditional-expression).
Johannes Schaub - litb
@Johannes: The program is a set of TUs, end of story. :)
Roger Pate
@Roger see how well i know you. One day before i told that you wouldn't say it's a set of cpp files! ahaha
Johannes Schaub - litb
+1  A: 

It means

//If this is true,
testNumber > 1
//testNumber is bigger than 1, then
true
//it is a true statemant, or
false
//else statement is faulse

or you can see it like this:

if(testNumber > 1) {
true
}
else {
false
}
+1  A: 

Ternary operator.

Your expression is for finding whether the value is true or false. For example,

boolean c = testNumber > 1 ? true : false;

Here based on the value of testNumber, c will be true or false.

Nikhil K