Thomas Sampson

Shorthand IF statement in C++

4 Comments

The C++ conditional operator (also known as the ternary operator) provides a succinct way to select a simple operation or assignment value based on a condition, without expressing the selection with the more cumbersome if/else syntax. If the condition is true, the leftmost expression is evaluated, otherwise the rightmost. Example usage can be seen below.

int a(5), b(10);
(a > b)? std::cout << a : std::cout << b; // operation
int c = (a > b)? a : b;                   // assignment
int d = (a > b)? ((a > 10)? 10 : a) : b;  // nested
Advertisements

Author: tomtech999

I have recently graduated with a 1st class degree in MComp Games Software Development at Sheffield Hallam University, focusing primarily on application development in C++, with experience in graphics programming, scripting languages, DVCS/VCS and web technology. In my spare time I enjoy Drumming, Reading and Snowboarding!

4 thoughts on “Shorthand IF statement in C++

  1. Hi, very nice post. I have been wonder’n bout this issue,so thanks for posting

  2. Hello i am a newb here. Hopefully i mighnt be able to contribute to this site, Just though i would say hey!

    cheers.

  3. I’m quite fond of the shorthand if statements in languages. So very useful. Perhaps a little harder to read (for those not familiar with it), but it does save a few lines for neatness sake.

    • I am in agreement Gaby. When used sparingly and in the appropriate situations, shorthand techniques such as this can vastly improve the readability and compactness of code. Unfortunately I have seen people abuse this type of approach by nesting numerous ternary operators to the point where the intent of the code becomes completely obfuscated.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s