C++ question: What does '?' mean?

Discussion in 'OT Technology' started by BoypussY, Dec 8, 2004.

  1. BoypussY

    BoypussY game over.

    Joined:
    Jun 27, 2000
    Messages:
    51,953
    Likes Received:
    0
    Location:
    IN YOUR HEAD
    for example:

    return 1+(hr>h1?hr:h1);


    what does the '?' and ':' mean in this statement?


    im guessing it means add the value of hr if hr>h1 is false, otherwise add the value of h1 if hr>h1 is true. :x:
     
  2. Scn64

    Scn64 Guest

    I think you're mostly correct but the true and false would be switched. hr would be added to 1 if hr>h1 is true. Otherwise h1 would be added. This is just my best guess though, I could easily be wrong.
     
  3. samm

    samm Next in Line

    Joined:
    Dec 22, 2000
    Messages:
    2,630
    Likes Received:
    0
    Location:
    San Jose, CA
    ? is a ternary operator

    expression1 ? expression2 : expression3;

    If expression1 is true, then the outcome is expression2. Otherwise, the outcome is expression3. This is commonly used in place of simple if/else statements which tend to make code difficult to read from time to time.
     
  4. Penguin Man

    Penguin Man Protect Your Digital Liberties

    Joined:
    Apr 27, 2002
    Messages:
    21,696
    Likes Received:
    0
    Location:
    Edmonton, AB
    Yep. Personally, I always find if/else cleaner, but some people seem to like ? : better :dunno:
     
  5. BoypussY

    BoypussY game over.

    Joined:
    Jun 27, 2000
    Messages:
    51,953
    Likes Received:
    0
    Location:
    IN YOUR HEAD
    thanks for the explanation guys.
     
  6. P07r0457

    P07r0457 New Member

    Joined:
    Sep 20, 2004
    Messages:
    28,491
    Likes Received:
    0
    Location:
    Southern Oregon
     
  7. WERUreo

    WERUreo Imua!

    Joined:
    Oct 15, 2003
    Messages:
    566
    Likes Received:
    0
    Location:
    Daytona Beach, Florida
    :werd:
    If that statement had been written as:
    Code:
    if (hr>h1)
         return 1+hr;
    else
         return 1+h1;
    
    he wouldn't have even needed to ask...
     

Share This Page