Question

I would like to create a C macro returning the scalar minimum for any type of static array in input. For example:

float A[100];
int B[10][10];
// [...]
float minA = MACRO_MIN(A);
int minB = MACRO_MIN(B);

How can I do so?

Was it helpful?

Solution

It can be probably be done with GCC extensions, but not in standard C. Other compilers might have suitable extensions, too. It will of course make the code fantastically hard to port. I would advise against it, since it's quite hard to achieve it will be "unexpected" and probably act as a source of confusion (or, worse, bugs) down the line.

You're going to have to declare a temporary variable to hold the max/min seen "so far" when iterating over the array, and the type of that variable is hard to formulate without extensions.

Also returning the value of the temporary is hard, but possible with GCC extensions.

To make the above more concrete, here's a sketch of what I imagine. I did not test-compile this, so it's very likely to have errors in it:

#define ARRAY_MAX(a)  ({ typeof(a) tmp = a[0];\
                         for(size_t i = 1; i < sizeof a / sizeof tmp; ++i)\
                         {\
                           if(a[i] > tmp)\
                             tmp = a[i];\
                         }\
                         tmp;\
                      })

The above uses:

  • ({ and }) is the GCC Statement Expressions extension, allowing the macro to have a local variable which is used as the "return value".
  • typeof is used to compute the proper type.
  • Note assumption that the array is not of zero size. This should not be a very limiting assumption.

The use of sizeof is of course standard.

As I wrote the above, I realize there might be issues with multi-dimensional arrays that I hadn't realized until trying. I'm not going to polish it further, though. Note that it starts out with "probably".

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