Detailed explanation of the use of ternary operator (conditional operator) in C/C++

The ternary operator consists of two parts. The one in front of "?" is the judgment condition. If the previous operation result is 1, that is, the previous condition is established, the execution result in front of ":" and the execution result after "?" will be executed, otherwise it will be executed. The expression after ":".

c=a>b?a:b;

Let's take a look at this line of code. First, the outermost brackets are to output the final result. If a>b, the previous expression is true and execution c=a. If a<b, the previous expression is false, execution c =b;

This is just a simple usage. Now let us think about this topic, how to use the ternary operator to find the maximum value of four numbers.

cout << (a > b ? (a > c ? (a > d ? a : d) : (c > d ? a : d)) : (b > c ? (b > d ? b : d) : (c > d ? c : d)));

Let's take a look at this line of code. First, the outermost brackets are to output the final result. Without it, the output result will only be 0 or 1. This is obviously not the result we want. The principle is to first divide it into three parts, the first part a > b ?, the second part (a > c ? (a > d ? a : d) : (c > d ? a : d)) :, the third part (b > c ? (b > d ? b : d) : (c > d ? c : d)), this is the outermost condition and result. We still need to split it. The second part can be divided into a > c ? , (a > d ? a : d), and: (c > d ? a : d), the third part is similar, this time it is almost the simplest form, the reason for using those multiple brackets is to see It will be easier to understand and write more clearly. Of course, except for the outer parentheses, you can omit it. I believe everyone can understand it. As long as you master this, it will almost not be a big problem.

Guess you like

Origin blog.csdn.net/m0_74316391/article/details/129967933