Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for max and min? (Objective-C)

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 MAXformula 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?

like image 683
stumped Avatar asked Nov 29 '22 16:11

stumped


2 Answers

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 or b). So you are right, int limits = MAX(4,8) just assigns 8 to limits and has nothing to do with finding the maximum value you can store in limits.

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.

like image 79
Roth Michaels Avatar answered Dec 06 '22 00:12

Roth Michaels


To break it apart:

The declaration:

#define MAX(a,b)

If a is greater than b, use a else use b:

( ((a) > (b)) ? (a) : (b) )

Then to create a MIN expression, use a similar form:

#define MIN(a,b) ( ((a) < (b)) ? (a) : (b) )
                        ^

Then to create a MAX3 expression, you can combine them:

#define MAX3(a,b,c) ( MAX(a, MAX(b,c)) )

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 to int limits = (4 > 8 ? 4 : 8). If you write MAX(x,++y), then y will be incremented twice if y is greater than or equal to x because it expands to: int limits = (x > ++y ? x : ++y).

like image 28
justin Avatar answered Dec 06 '22 02:12

justin