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) )
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 */
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
could you walk me through whats happening there?
largest is being assigned the (largest of x and (the largest of y and z)).
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
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.
Hope is the first step on the road to disappointment.
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...
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
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; }
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
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.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Im using visual studio 6