#include <stdio.h>

#define max( a, b) a > b ? a:b 

int main()
{
        int i, j = 10;

        int k = 15;

        for( i = 0; i < max( j, k ); i++ ) {
                printf( "\nhi" );
        }

        return 0;
}

The above code generates an infinite loop.. Why so ??
Why the value of expression

i < max( j, k)

is 15 ? Why not 1 or 0 ??

Another case of the failed expanded macro. If you expand that macro you will get the following:

int main()
{
        int i, j = 10;

        int k = 15;

        for( i = 0; i < j > k ? j:k; i++ ) {
                printf( "\nhi" );
        }

        return 0;
}

It is general good practice to wrap macros in parenthesis to avoid this type of behavior. Consider the following as a replacement for your macro and see what you get:

#define max( a, b) ((a) > (b) ? (a):(b))

Which will then result in

for( i = 0; i < ((j) > (k) ? (j):(k)); i++ ) {

which is really what you want.

#define is a textual substitution. The expression expands to

i < j > k? j: k

I leave it as an exercise to figure out the actual precedence. To avoid such mess, you need to be more explicit:

#define max( a, b) (a > b ? a:b)

Notice an extra pair of parenthesis.
PS: even now the macro poses a number of problems.

Thanks L7Sqr and nezachem. That was a blunder I did in-spite of knowing the rule of substitution.
@nezachem: When you say about the problems of macros, what all problems are you talking about..
Like passing j++ and k++ etc ??
Please provide some cases when there will be unexpected output.
Thanks once again

Like passing j++ and k++ etc?

Yes. Expressions a and b are evaluated twice. So the side effect (if any) happens twice (which is already unhealthy), and may lead to an undefined behaviour.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.