如何使用条件(三元)运算符? [英] How do I use the conditional (ternary) operator?

查看:78
本文介绍了如何使用条件(三元)运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道如何用C ++兼容语言编写 "A?B:C" 语法.

I've always wondered how to write the "A ? B : C" syntax in a C++ compatible language.

我认为它的工作方式类似于:(伪代码)

I think it works something like: (Pseudo code)

If A > B
   C = A
Else
   C = B

任何资深的C ++程序员都请帮帮我吗?

推荐答案

它的工作原理如下:

(condition) ? true-clause : false-clause

它在分配操作中最常用,尽管它还有其他用途.三元运算符?是缩短if-else子句的一种方式,在其他语言中也称为即时if语句( IIf(condition,true-clause,false-clause)(例如,在VB中).

It's most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (IIf(condition,true-clause,false-clause) in VB, for example).

例如:

bool Three = SOME_VALUE;
int x = Three ? 3 : 0;

bool Three = SOME_VALUE;
int x;
if (Three)
    x = 3;
else
    x = 0;

这篇关于如何使用条件(三元)运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆