Sillyon
Sillyon

Reputation: 45

find min(a,b,c) or max(a,b,c) with using #define macro preprocessor in c

this is the question what asked in my exam is: "write cource code of min(a,b,c) with macros in c language."

#define min(a,b,c) ((a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c)))

is there better way to solve min/max(x,y,z) problem?

Upvotes: 1

Views: 6655

Answers (3)

Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

I think the key point you missed in the question is "macros" not and macro. You can simplify this a lot if you break it down further as follows -

#define min2(a, b) ((a) < (b) ? (a) : (b))
#define min(a, b, c) (min2(min2((a), (b)), (c)))

This is also much easier to comprehend.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881653

Your solution, and all portable macro-based ones, are a good reason why the use of macros should be limited as much as possible. Nowadays, I pretty much use them for little more than conditional compilation.

In terms of defining constants, you are better off with enumerations.

In terms of function-like macros, you're far better off using functions which you can suggest to the compiler to be made inline, or just rely on the compiler to figure that out (they're usually pretty good at that).


The reason why function-like macros are a bad idea is because, being simple text substitution, the sequence:

#define mymax(a, b) (a) > (b) ? (a) : (b)
int x = mymax(y++, complexFunction());

will actually evaluate y++ and/or call complexFunction() more than once, something a real function would not do.

By all means use them provided you understand the limitations. Me, I'll rely on the compiler doing the right thing for functions so that I don't have to worry about the dark corners of C too much :-)

Upvotes: 3

D&#250;thomhas
D&#250;thomhas

Reputation: 10048

Yes. Write functions.

int min2( int x, int y        ) { return x < y ? x : y; }
int min3( int x, int y, int z ) { return min2( x, min2( y, z ) ); }

If you wish for pretty, you can write some variadic macros that choose the correct function based on the number of arguments. Those are a bear to write, though.

If you wish to stick with only macros, your choices are much less friendly. Ajay B’s solution (fixed as per commentary) works well.

GCC supports some nice extensions that eliminate re-evaluation issues:

#define max(a,b) \
   ({ typeof (a) _a = (a); \
       typeof (b) _b = (b); \
     _a > _b ? _a : _b; })

You can then easily write any n-ary macro you wish that does not suffer from parenthetical or re-evaluation horrors.

#define max3(a,b,c) max(a,max(b,c))

Upvotes: 2

Related Questions