Gregc. wrote On 05/03/06 17:40,:
Hi
I am trying to find the min of a list of numbers. For example, if a
user enters 10 numbers 1,2,3,4,5,6,7,8,9,9 then the min would be 1.
I've looked as past posts on the topic, and there was one that
mentioned macro's. Could someone explain how do macro's (if at all)
work within the C programming environment.
A guess: You're thinking of using a macro that
calculates the minimum of two numbers, e.g.,
#define MIN(a,b) ((a) < (b) ? (a) : (b))
... and then extending it via "nesting" to form macros
that calculate the minima of larger populations
#define MIN4(a,b,c,d) MIN(MIN(a,b), MIN(c,d))
#define MIN8(a,b,c,d,e,f,g,h) \
MIN(MIN4(a,b,c,d), MIN4(e,f,g,h))
#define MIN10(a,b,c,d,e,f,g,h,i,j) \
MIN(MIN8(a,b,c,d,e,f,g,h), MIN(i,j))
You'd then apply this super-macro to your list of ten
numbers
x = MIN10(a[0], a[1], a[2], a[3], a[4],
a[5], a[6], a[7], a[8], a[9]);
If that's what you're intending, my advice is "Don't!"
That innocent-appearing final line expands to
x=((((((((a[0])<(a[1])?(a[0])
a[1])))<(((a[2])<(a[3])?(
a[2])
a[3])))?(((a[0])<(a[1])?(a[0])
a[1])))
((a[2])<
(a[3])?(a[2])
a[3])))))<(((((a[4])<(a[5])?(a[4])
a[5])
))<(((a[6])<(a[7])?(a[6])
a[7])))?(((a[4])<(a[5])?(a[4]
)
a[5])))
((a[6])<(a[7])?(a[6])
a[7])))))?(((((a[0])<
(a[1])?(a[0])
a[1])))<(((a[2])<(a[3])?(a[2])
a[3])))?(
((a[0])<(a[1])?(a[0])
a[1])))
((a[2])<(a[3])?(a[2])
a
[3])))))
((((a[4])<(a[5])?(a[4])
a[5])))<(((a[6])<(a[7
])?(a[6])
a[7])))?(((a[4])<(a[5])?(a[4])
a[5])))
((a[
6])<(a[7])?(a[6])
a[7])))))))<(((a[8])<(a[9])?(a[8])
a
[9])))?(((((((a[0])<(a[1])?(a[0])
a[1])))<(((a[2])<(a[3
])?(a[2])
a[3])))?(((a[0])<(a[1])?(a[0])
a[1])))
((a[
2])<(a[3])?(a[2])
a[3])))))<(((((a[4])<(a[5])?(a[4])
a
[5])))<(((a[6])<(a[7])?(a[6])
a[7])))?(((a[4])<(a[5])?(
a[4])
a[5])))
((a[6])<(a[7])?(a[6])
a[7])))))?(((((a[
0])<(a[1])?(a[0])
a[1])))<(((a[2])<(a[3])?(a[2])
a[3])
))?(((a[0])<(a[1])?(a[0])
a[1])))
((a[2])<(a[3])?(a[2]
)
a[3])))))
((((a[4])<(a[5])?(a[4])
a[5])))<(((a[6])<
(a[7])?(a[6])
a[7])))?(((a[4])<(a[5])?(a[4])
a[5])))
((a[6])<(a[7])?(a[6])
a[7])))))))
((a[8])<(a[9])?(a[8]
)
a[9]))));
This expression contains forty-five relational operators with
two operands each, forty-five ternary operators with three
operands each, and one hundred thirty-six references to the
array `a'. Even if it doesn't choke the compiler, it will
surely produce more (and possibly slower) code than the obvious
for-loop. Also, you wind up with inflexible code that deals
only with ten-element lists: you can't adapt to an eleven- or
nine- or hundred-element list without changing the source.
The KISS principle applies here: "Keep It Simple, Stupid!"