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:
using namespace std;
// значение этой переменной будет изменять пользователь
bool variable = true;
cout << "Выполнение каких-то транзакций по счету карты...\n";
cout << "Вы хотите выполнить другую операцию (1 - да, 0 - нет)? ";
cin >> variable;
variable == 1 ? cout << "Выберите операцию!\n..........\n\n" : cout << "До свидания! Не забудьте взять чек!\n\n";
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:
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.
using namespace std;
int firstDigit = 0;
int secondDigit = 0;
int max = 0;
int min = 0;
cout << "Введите firstDigit - первое число:";
cin >> firstDigit;
cout << "Введите secondDigit - второе число:";
cin >> secondDigit;
// используя тернарный оператор, определяем максимум
// и сразу записываем его в переменную max
max = (firstDigit > secondDigit) ? firstDigit : secondDigit;
// так же определяем и записываем min
min = (firstDigit < secondDigit) ? firstDigit : secondDigit;
/*// или так:
if (max == firstDigit)
min = secondDigit;
min = firstDigit;*/
cout << "Максимум = " << max << endl;
cout << "Минимум = " << min<< endl;
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.