Do you know what is trinocular expression?

Table of contents

What is a trinocular expression?

use

1. Single use

2. Nested use


What is a trinocular expression?

1. Trinocular expression is a common expression in programming, it can effectively help us solve some problems.

2. The ternary expression consists of three parts, namely: conditional expression and result expression

Don’t understand, let’s give an example: a>b ? a : b;

The above execution flow is: first calculate the value of the relational expression

  • If the value is true, the value of expression1 is the result of the operation
  • If the value is false, the value of expression 2 is the result of the operation

use

1. Single use

For some alternative branch structures, simple conditional operators can be used instead. For example:

if(a<b)
    min=a;
else
    min=b;

 Equivalent to:

min=(a<b)?a:b;

Explain again: where "(a<b)?a:b" is a "conditional expression", it is executed like this

  • If a<b is true, the expression takes the value of a, otherwise it takes the value of b.
  • The conditional operator consists of two symbols "?" and ":", and requires three operands, so it is also called the ternary operator, which is the only ternary operator in the C language.

Its general form is:

expression1?expression2:expression3;

2. Nested use

#include<bits/stdc++.h>
#include<windows.h>
#include<ctime>
using namespace std;
int main()
{
	int a = 2;
    int b = 3;
    int c = 4;
    int d = a > b ? 0 : c > b ? 1 : 0;
    // 可以用括号分开来看,会比较清楚
    // int d = a > b ? 0 : (c > b ? 1 : 0);
    printf("值1:%d",(c > b ? 1 : 0));
    printf("值2:%d" ,d);
    return false;
    

}

Output result:

值1:1
值2:1

Equivalent to:

        if (a > b) {
            d = 0;
        } else {
            if (c > b) {
                d = 1;
            } else {
                d = 0;
            }
        }

It’s a little watery today, but it’s definitely not going to be watery when I get the closed beta tomorrow and the day after tomorrow!

 

Guess you like

Origin blog.csdn.net/qiuweichen1215/article/details/130893362