What is the ternary operator in C language

王林
Release: 2020-07-15 13:57:28
Original
37915 people have browsed it

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
Copy after login

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);
Copy after login

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);
}
Copy after login

Run result:

6,0
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template