The basics of programming in c++ for beginners

Ternary statement ? : in C++

Hope, you are well dealt with the theme select if and else statements and you are not too difficult to solvetasks 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 conditionvariable == 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 then a second code. 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, valuefirstDigit   recorded in max , if false, the value is written secondDigit.    Further, it should be understood all. Compile:

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

The program works fine!

Good about the ternary operator is told in this video lesson.

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.

13 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:

    variable == 1 ? cout << "Выберите операцию!\n..........\n\n" : cout << "До свидания! Не забудьте взять чек!\n\n";

    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:

    cout << (variable ? "Выберите операцию!\n..........\n\n" : "До свидания! Не забудьте взять чек!\n\n");

    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:

    max = (firstDigit > secondDigit) ? firstDigit : secondDigit;

    // так же определяем и записываем min
    min = (firstDigit < secondDigit) ? firstDigit : secondDigit;

    replaced as (about):

    a > b ? max = a, min = b : max = b, min = a;

    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:


        e = a < b ? b < c ? 1 : 2 : c < d ? 3 : 4;

        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.

  2. and can give an example to the BBC using the ternary operator to search for a minimum of three numbers? I can not figure out((

  3. Hi,a free lotto ticket has been sent to you. Follow the link ->> https://forms.yandex.ru/cloud/62eb57d1a73baf103e535cb5/?hs=423814bc7d948078983f9a5e855dfdc7& says:

    6hn057

  4. In the last listing, on the 26th line, there is an error – if (max == firstDigit), there should be written if (firstDigit < secondDigit)

  5. rrrFer: I think you first need to build a fence and then write on it. Moreover, on your . Fences come in different configurations

Leave a Reply

Your email address will not be published. Required fields are marked *