Question

If I need a simple function for my program, lets say to determine max of two numbers, is it better to define it like:

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

or

int getmax(int a, int b)
{
    return a>b?a:b;
}

I made a simple program that prints getmax(a, b)

#include<stdio.h>
#define getmax(a, b) ((a)>(b)?(a):(b))

int main()
{
    int i, j;
    for( i = 0; i < 100; i++)
        for( j = 0; j < 100; j++)
            printf("%d\n", getmax(i, j));
    return 0;
}

and

#include<stdio.h>

int getmax(int a, int b)
{
    return a>b?a:b;
}

int main()
{
    int i, j;
    for( i = 0; i < 100; i++)
        for( j = 0; j < 100; j++)
            printf("%d\n", getmax(i, j));
    return 0;
}

I tested both programs 10 times and calculated the average runtime. For the first program average is 0.8880s and for the second program average is 0.8575. What is better to use and is there any other difference than runtime?

Was it helpful?

Solution

int getmax(int a, int b)
{
    return a>b?a:b;
}

is better than

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

Because consider doing

getmax(a++,b++);

With define macro you get

((a++)>(b++)?(a++):(b++));

And this is propably not what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top