C++,java,python,scala,shell ternary operation summary

1. Background

In the actual work scene, various languages ​​are often mixed together. When mixing, the brain often short-circuits and confuses various grammars, or a certain language has not been written for a while and is forgotten, such as trinocular arithmetic. In order to facilitate memory search, it is hereby recorded.

2. c++ and java realize ternary operation

There are standard ternary operators in the syntax of c++ and java. details as follows

c++ code:

void func() {
    int a = 3, b = 2;
    int maxnum = a > b ? a : b;
    cout<<"maxnum is: "<<maxnum<<endl;
}

java code:

    public void test4() {
        int a = 3, b = 2;
        int maxnum = a > b ? a : b;
        System.out.println("maxnums is: " + maxnum);
    }

It can be seen that both c++ and java have a standard ternary operator? :, just use it directly.

3.python trinocular operation

There is no standard ternary operator in the python grammar, and it is very convenient to use the if else grammar to simulate the ternary operator.

exp1 if contion else exp2
def func():
    a, b = 3, 2
    c = a if a > b else b
    print(c)

4. Scala trinocular operation

There is no standard ternary operator in scala? :, similar to python, you can also use if else statement to simulate ternary operation.

  def func() = {
    val (a, b) = (3, 2)
    val maxnum = if (a > b) a else b
    println(maxnum)
  }

Note that the difference between scala and the if else expression in python is that it essentially uses the automatic inference syntax in scala. Any expression in scala has a value, and the value of the if else expression is the last line of code in each branch. result.

5. shell trinocular operation

There are also similar ternary expressions in the shell, and the ?: syntax in the shell, see the following example.

#!/bin/bash

a=3
b=2
c=$((a>b?a:b))
echo "c is: "$c

The $(( )) expression, combined with the ?: ternary operator, can achieve the desired effect.

Guess you like

Origin blog.csdn.net/bitcarmanlee/article/details/129581633