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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top