Ternary statement ? : in C++




тернарный оператор ?: C++

Hope, you are well dealt with the theme select if and else statements and you are not too difficult to solve tasks on this topic. The same lesson we continue to learn the basics of programming in C ++, and get acquainted with another selection operator (branch) – this is ternary statement ? :

It is usually used in cases, and if the condition code, that it is necessary to perform, the scan conditions, very simple. For example, ask the user whether he wants to continue working in the program or want to get out of it. The syntax is:

тернарный оператор ?:

First, we need to write a necessary condition for us and put a question mark behind it ? . Further, in the same line, after the question mark write first a simple command (code), which will be performed, if the condition returns true (true). After this command, we put a colon : and write a second command (code). This second team after the colon, executed only if, if the condition returns false (false).

Example. Suppose the user withdraws money from an ATM. He had the operation, and the screen should appear question: “You want to perform another operation?” The user is to make a choice (Yes or no) and press the corresponding button. We organize the selection of the following program:

The user makes a selection and enters a value – string 13. In string 15 we check the entered value. If the condition variable == 1 returns true (that is, if the variable is really 1), the executed code, located after the question mark ? . And the, that is after the colon : – ignored. Otherwise, if the user entered 0, ignored the code located between ? and : , and the second code is executed. Here is the result of work if introduced 1:

тернарный оператор ?:

if 0:

тернарный оператор ?:

Here is another interesting example. In him, using the ternary operator, determined minimum and maximum number of the two values, who will introduce the user.

Consider the string 20. The code will run as – first run for the ternary operator, will return a value based on the delivered condition, and after the value is written in the variable max. If the condition (firstDigit > secondDigit) – truth, value firstDigit recorded in max , if false, the value is written secondDigit. Further, it should be understood all. Compile:

тернарный оператор ?:

The program works fine!

A little about the ternary operator is told in this video tutorial (15--s minutes). Besides, it addresses the same statement multiple choice switch (17--s minutes) and conditional statements if and else




Finally, add, it is not recommended to some agreements on the coding to use the ternary operator because, it reduces code readability. But it is necessary to know about, since no one can predict, what codes need to find and read the future. Coding conventions longer can be found in our article Formatting source code.

Would you say “Thank you” for author? – share the article with your friends. To do this, click on your social network button below this article. I will be pleased! :)

Newsletter lessons:


Agree to receive notifications from purecodecpp.com to my e-mail

Date
page
Ternary statement ? : in C++
Rating
5

5 thoughts on “Ternary statement ? : in C++

  1. IMHO should be added, that not all coding conventions generally are allowed to use the ternary statement, tk. often falls easy readability of code.

    Like this:

    certainly better to do.
    1) You have variable – a variable of type bool, therefore variable == 1 is replaced by a variable.
    2) Do you compare Boolean variables with integer, it can confuse other programmers.
    3) According to some agreements on the coding when compared to equality must be a constant expression in the left side (failed to write variable = 1 instead of variable == 1, tk. 1 = Variable will generate an error at compile).
    4) I would have written as:

    A number of comrades advised to instead write a variable true == variable, but here it is possible to argue :).

    In general all of the code such. I have it:

    replaced as (about):

    then it makes no sense to carry out a comparison 2 times and it makes no sense to take the condition in parentheses

    The last example shows, that the colon is not shared by one team and the other team (as your figure), and expression. Besides, I would mention, that the comma operator returns the same value.

    1. rrrFer (aka Vladimir), it is wonderful, that you so carefully proofread our article. What can you say to your comment? I will say this – improve and optimize the code can be up to infinity. Because of your readers will see the commentary, that same task can be solved in different ways and that there are different options for dealing with variables bulevksimi. In your case is more optimized code. But my code is painted in more detail (so we focus primarily on newcomers) and similarly,, like your code, He has the right to life.
      P.S. Swearing of your comments deleted and in the future they would not like to see

      1. ummm… my comments were swearing? )

        I do not even proofread articles, I looked at the drawing and the source code.

        The point here is not in the optimization, and potential doorposts, that will never appear if you follow some agreements.

        well, for example, When you compare a Boolean variable to an integer, what's happening? – It is going to bring a bool to int, while fixed in the standard, that corresponds to the true unity, а false – zero. But if an integer cast to bool, then 2 == True would be to return true (but it is not, Although all sorts of students and schoolchildren can doubt, because they did not read standard).

        About the agreement, I wrote to the, there are pitfalls. For example once you write a class of complex numbers and reload it for a comparison operator, and the cast operator to the type bool. I think, that can receive a different and dangerous behavior in this case. That is. correct to compare the variables of the same type, and not expect that it casts automatically.

        I think, that the emphasis should be done on a case, when it is necessary to use the ternary operator, i.e.. when it is useful. Without it, all you can do, but it is syntactic sugar, which are often abused pupils and students. write like this about:

        We have an agreement to coding were listed cases where the operator is allowed to use in order to prevent such code here.

      2. We fully agree, without that the ternary operator can do in programming. But you have to know, such that there is, what it looks like and how it works. You never know, some people's code you have read and that there will be used.

Leave a Reply

Place code in tags: <pre class="lang:c++ decode:true ">YOUR CODE</pre>