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

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

问题描述

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

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



 如果A> B 
C = A
Else
C = B

解决方案

它的工作原理是这样的:

 (条件)? true-clause:false-clause 

它最常用于赋值操作,好。三元运算符是缩短if-else子句的一种方法,也称为其他语言的立即if语句( IIf ,true-clause,false-clause)在VB中,例如)。



例如:

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

相同

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


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

Will any veteran C++ programmer please help me out?

解决方案

It works like this:

(condition) ? true-clause : false-clause

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

For example:

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

is the same as

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

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

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