Home  >  Article  >  Backend Development  >  What is the ternary operator in C language

What is the ternary operator in C language

王林
王林Original
2020-07-15 13:57:2837914browse

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].

What is the ternary operator in C language

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn