|Access||Adobe photoshop||Algoritmi||Autocad||Baze de date||C||C sharp|
|Calculatoare||Corel draw||Dot net||Excel||Fox pro||Frontpage||Hardware|
|Php||Power point||Retele calculatoare||Sql||Tutorials||Webdesign||Windows|
|Asp||Autocad||C||Dot net||Excel||Fox pro||Html||Java|
This operator is unusual because it has three operands. It
is truly an operator because it produces a value, unlike the ordinary if-else
statement that you’ll see in the next section of this chapter. The expression is of the form
boolean-exp ? value0 : value1
If boolean-exp evaluates to true, value0 is evaluated and its result becomes the value produced by the operator. If boolean-exp is false, value1 is evaluated and its result becomes the value produced by the operator.
Of course, you could use an ordinary if-else statement (described later), but the ternary operator is much terser. Although C prides itself on being a terse language, and the ternary operator might have been introduced partly for efficiency, you should be somewhat wary of using it on an everyday basis – it’s easy to produce unreadable code.
The conditional operator can be used for its side effects or for the value it produces, but in general you want the value since that’s what makes the operator distinct from the if-else. Here’s an example:
You can see that this code is more compact than what you’d need to write without the ternary operator:
The second form is easier to understand, and doesn’t require a lot more typing. So be sure to ponder your reasons when choosing the ternary operator.
Politica de confidentialitate|
Adauga cod HTML in site