C Programming: Macro functions that return values

A few weeks ago I was searching around the Internet for an explanation of how to write a macro (preprocessor) function that returns a value.  All I could find was various articles suggesting something like this:

#define MAX(A,B)  ((A > B) ? A : B)

However, I was looking for a more complicated example for instance something with a loop like this:

#define MAX(A,B)  ((A > B) ? A : B)

#define HIGHEST(ARRAY) /* .... */

int main (void)
{
    int A[] = { 1, 2, 4, 3 };

    printf("%d\n", HIGHEST(A));

    return 0;
} 

All the articles I could find were suggesting adding an out parameter to the function to return the highest value.  After a lot of searching around I eventually gave up and used inline functions instead.  However, I recently stumbled upon an example of how this can be achieved without resorting to additional output parameters.  It is actually quite simple as I expected.  All you need to do is enclose the body in parentheses and braces and ensure the last statement evaluates to the required value.  I thought I should share this just in case someone else is interested.  Here is a complete example written in C:

#include <stdio.h>

#define MAX(A,B)  ((A > B) ? A : B)

#define HIGHEST(ARRAY) \
({ \
    int i; \
    typeof (ARRAY[0]) ret = ARRAY[0]; \
    for (i = 1; \
         i < (sizeof(ARRAY) / (sizeof(typeof (ret)))); \
         i++) \
    { \
        ret = MAX(ret, ARRAY[i]); \
    } \
    ret; \
})

int main (void)
{
    int A[] = { 1, 2, 4, 3 };

    printf("%d\n", HIGHEST(A));
}

The output of this application is: 4

Note: This example was tested with gcc.

Comments

Popular Posts