Home  >  Article  >  Backend Development  >  What is the operator "?:" in C language?

What is the operator "?:" in C language?

王林
王林Original
2020-05-11 14:28:2262262browse

What is the operator

The "?:" in C language is a ternary operator, which connects three objects. It is the only ternary operator in C language, also known as Conditional operator.

Its general form is as follows:

表达式a?表达式b:表达式c

Its execution steps are as follows:

1. Calculate the value of expression a.

2. If the value of expression a is 1, execute expression b.

3. If the value of expression b is 0, 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, and if it is true, execute "?" The first expression after the number, otherwise the second expression is executed.

Specific example:

#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);
}

Running results:

6,0

Recommended tutorial: c language tutorial

The above is the detailed content of What is the 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