Opperators

This is a discussion on Opperators within the C++ Programming forums, part of the General Programming Boards category; As Iv'e been journeying through verious texts iv'e come accross simmalar lines of code such as this one a few ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,540
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  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,318
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21