Ternary Operator (C++)

1. Introduction

  • Fixed format ? :
  • Ternary operator: can be used in assignment statements
  • Ternary operation expression: <Expression 1>? <Expression 2>: <Expression 3>
    Note: The meaning of the "?" operator is: first find the value of expression 1, if it is true, then execute the expression 2, and return the result of expression 2; if the value of expression 1 is false, then execute expression 3 and return the result of expression 3.

Second, the application of the ternary operator

Assignment: Conditional judgment achieved by the ternary operator: Assign an lvalue if the condition is true, assign an rvalue if the condition is not

	int a=10, b=20, z;
	z =  (a>b) ? a : b;//条件成立赋左值z=a,条件不成立赋右值z=b
	=>z=2

Select statement execution : the statement on the left is executed if the condition is satisfied, and the statement on the right is executed if the condition is not satisfied

	int i = 1, j = 2, k = 3;
	i == 0 ? (i = j + k, j = 5) : (k++, k++);
	cout << i << ' ' << j << ' ' << k << endl;
	输出 1 2 5
	int i = 1, j = 2, k = 3;
	i == 1 ? (i = j + k, j = 5) : (k++, k++);
	cout << i << ' ' << j << ' ' << k << endl;
	输出 5 5 3

Guess you like

Origin blog.csdn.net/weixin_45341339/article/details/111150349