Thread: Opperators

  1. #1
    Master n00b Matty_Alan's Avatar
    Join Date
    Jun 2007
    Location
    Bloody Australia Mate!
    Posts
    96

    Opperators

    As Iv'e been journeying through verious texts iv'e come accross simmalar lines of code such as this one a few times:

    Code:
    #define MIN(X,Y) ( ((X) < (Y)) ? (X) : (Y) )

    Now, I know what this does... to a degree the macro part and format i understand but it's the opperators '?' and ':' I don't have a clue what they mean and none of the texts i'm reading appear to explain it.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    K&R calls it the conditional operator, see A7.16 of K&R-2.

    a = MIN(x,y)
    is
    if ( x < y ) a = x ; else a = y;
    but in a form you can use in an expression.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Master n00b Matty_Alan's Avatar
    Join Date
    Jun 2007
    Location
    Bloody Australia Mate!
    Posts
    96
    Oh ok,

    so basicly the '?' is the opperator equivilant of the 'IF' command and ':' is the same as Else, just a little differently written

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Yes, but you have to must use them both together and the syntax isn't exactly the same (e.g. the condition goes after the if but before the ?).

  5. #5
    Internet Superhero
    Join Date
    Sep 2006
    Location
    Denmark
    Posts
    964
    You can look up the syntax here: http://en.wikipedia.org/wiki/&#37;3F:

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    The C++ Standard Library has min() from <algorithm> which does the same thing more safely, without the macro.

    http://www.cplusplus.com/reference/algorithm/min.html

Popular pages Recent additions subscribe to a feed