#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2006
    Posts
    102
    Rep Power
    0

    Max function in C?


    Is there a built-in function in C that would allow me to get the maximum between two values or a set of values?

    maxVal = max(val1, val2)

    Thanks!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    May 2004
    Posts
    3,417
    Rep Power
    887
    For float, double and long double there's the fmin(), fminf(), fminl(), fmax(), fmaxf(), fmasl() functions. I don't believe there is one that is portable for the various int values, but I'd bet most compilers have min() and max() macro's. If you have to do it in C, the easiest way is to write macro's like this:

    Code:
    #ifndef max
    	#define max( a, b ) ( ((a) > (b)) ? (a) : (b) )
    #endif
    
    #ifnef min
    	#define min( a, b ) ( ((a) < (b)) ? (a) : (b) )
    #endif
    Microsoft defines these in <minmax.h>.
    I no longer wish to be associated with this site.
  4. #3
  5. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    Be aware of course, that macros aren't always a good solution. For instance, it is possible to mess up the above by doing this:
    x = min(a++, b--);

    As long as you don't put expressions like that in there, you should be ok though.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2006
    Posts
    102
    Rep Power
    0
    tHANKS!

    I don't have those cases that you mentioned so I think I'm ok with this!

IMN logo majestic logo threadwatch logo seochat tools logo