Home >Backend Development >C#.Net Tutorial >What is the ternary operator in C language
The ternary operator in C language is: "?:". The ternary operator connects three objects and is the only ternary operator in the C language. It is also called the conditional operator. Its general form is: [expression a? expression b: expression c].
The ternary operator in C language is: "?:". This operator connects three objects and is the only ternary operator in C language. operator, also known as conditional operator.
(Recommended learning: C Language Tutorial)
The general form is as follows:
表达式a?表达式b:表达式c
The execution steps are as follows:
1. Calculation The value of expression a;
2. If the value of expression a is 1, then execute expression b;
3. If the value of expression b is 0, then execute expression c;
Note: When there are multiple ternary operators, they are operated in order from right to left.
For example, the following two expressions are equivalent.
a<b?b:c>b?c:b; a<b?b:(c>b?c:b);
Analysis: The ternary operator determines the truth value of the conditional expression. If it is true, the first expression after the "?" symbol will be executed, otherwise the second expression will be executed.
Code implementation:
#include<stdio.h> void main() { int x=5; //定义一个整数变量 int y=++x>5?0:1; //通过三目运算符对x进行运算 //判断++x是否大于5,若大于5则将0赋予变量y,否则将1赋予变量y printf("%d,%d\n",x,y); }
Run result:
6,0
The above is the detailed content of What is the ternary operator in C language. For more information, please follow other related articles on the PHP Chinese website!