This is a part of a book I'm reading to learn Objective-C.
The following defines a macro called MAX that gives the maximum of two values:
#define MAX(a,b) ( ((a) > (b)) ? (a) : (b) )
And then there are some exercises in the book that asks the reader to define a macro (MIN
) to find the minimum of two values and another that asks to define a macro called MAX3
that gives the maximum of 3 values. I think these two definitions will look similar to MAX
, but I don't understand how the MAX
formula finds the maximum value. I mean if I just did this
int limits = MAX (4,8)
It'll just assign limits
the value of 8. What does that have to do with finding a variable's maximum value?
To break it apart:
The declaration:
If
a
is greater thanb
, usea
else useb
:Then to create a
MIN
expression, use a similar form:Then to create a
MAX3
expression, you can combine them:Specifically, this macro's intended to be used with scalars (C builtins) which can be compared using
<
or>
. If you passed an objc variable, it would result in comparison of addresses and MAX would return the one with the higher address (it would be very rare if you actually wanted to compare addresses of objc instances).Also note that this is the classic example of how macros can bite you. With macros, the preprocessor simply expands (textual copy/paste) the parameters in place, so:
int limits = MAX (4,8)
literally expands toint limits = (4 > 8 ? 4 : 8)
. If you writeMAX(x,++y)
, theny
will be incremented twice ify
is greater than or equal tox
because it expands to:int limits = (x > ++y ? x : ++y)
.I think you are confusing value and variable. The macro example you listed expands to a comparison between two values and returns the greater of the two values (i.e. which is greater,
a
orb
). So you are right,int limits = MAX(4,8)
just assigns8
tolimits
and has nothing to do with finding the maximum value you can store inlimits
.The header limits.h defines many values like
INT_MAX
that will tell you information about the min/max values of variable types on your system.Algorithm for max (Objective-C)
generally, you will use a MAX() or MIN() macro to get whichever is the higher/lower of a pair of variables, or of a variable and a constant, or even a pair of macro constants or other non-literal constant expressions. you generally won't supply 2 literal constants as you have done in your question.