Oddities: Conditional Operator

The conditional operator is rather strange, but is very useful. (By the way, an operator is something that acts upon two or more values, such as the addition ‘+’ operator.) In many cases (or at least frequent enough for them to make up a new operator), programmers have had to determine the largest or the smallest of two values, and use the corresponding (largest or smallest) value. Normally, the code would be like this:

if (number1 > number2)
     return number1;
     return number2;

This became cumbersome. Introducing, the conditional operator:

return (number1 > number2) ? number1 : number2;

This does the same thing as the code above. The parts in bold are the required syntax; any valid expression, constant, or variable can be placed in between.

There are three parts to the conditional operator: the condition, and the two “paths”.

The condition is a boolean condition, one that would otherwise trigger an if-statement. If that is true, number1 is returned; otherwise number2 is returned.

That’s all there is to it.

Leave a comment


  1. Ethan

     /  November 10, 2010

    Ugh!!! Hurry up! I need to learn objective C before the iPhone app bubble bursts!

  2. Ethan

     /  November 15, 2010

    Haha! Thanks man! … Just hassling you, just hasslin’.

  1. Extension 4: What goes Inside the if() Statement « Programming for iOS
  2. The Jungle, Part 1 « Programming for iOS

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

  • Welcome

    My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

  • Contact Me

    If you need to contact me for any reason, feel free to send me an email.
  • The Giving Spirit

    If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 220 other followers

  • Back to the Past

    October 2010
    S M T W T F S
  • Time Machine

  • You count!

  • Worldwide Stats

    free counters
%d bloggers like this: