Hi,
I have a macro that tests for the largest of two numbers:
How would I code it to test for three?Code:Largest(x,y) ( ((x) > (y))? (x): (y) )
Printable View
Hi,
I have a macro that tests for the largest of two numbers:
How would I code it to test for three?Code:Largest(x,y) ( ((x) > (y))? (x): (y) )
Code:#include <stdio.h>
#define Largest(x,y) ( ((x) > (y))? (x): (y) )
int main(void)
{
int x = 2, y = 1, z = 3;
int largest = Largest(x,Largest(y,z));
printf("largest = %d\n", largest);
return 0;
}
/* my output
largest = 3
*/
could you walk me through whats happening there?
largest is being assigned the (largest of x and (the largest of y and z)).
The result of the inner macro call are called against the third value. Since the first (inner) result is the larger of those two, it works fine when it's called again, giving you the result of that value compared to a third value.
Quzah.
doesnt z have to be in the macro definition?
Does it look like it?
A macro is a text substitution; what appears to be code is automagically replaced by the replacement text...
so, the inner Largest finds the larger of y and z, which is z, then the outer Largest takes that and compares it to x to find the final result?Code:int largest = Largest(x,Largest(y,z));
Sometimes it can be helpful to examine the preprocessor output.
Code:int main(void)
{
int x = 2, y = 1, z = 3;
int largest = ( ((x) > (( ((y) > (z))? (y): (z) )))? (x): (( ((y) > (z))? (y): (z) )) );
printf("largest = %d\n", largest);
return 0;
}
:eek: Thats scary. Ive never looked at that stuff before. Thats whats being processed behind the scenes? Is that opened as a file in the project folder or can you see it through a command?
Most compilers allow some option to output the work of the preprocessor. This was an editing of the uglier output with BC55.
Im using visual studio 6