1

How can I write a Standard C( C89 or C99 compliant) macro that is independent of type specifier?

Specifically, I want to write a macro to compare two numbers which can be of signed type or unsigned type, 8-bits, 16-bits, 32-bits, 64-bits.

What I'm looking for, is something like this:

           int c,  a , b;
           uint16_t p, q, r;

                .
                .
                .

           c = min(a, b);

                .
                .
                .

           r = min(p, q);
                .
                .
                .

ie, the same macro 'min' can be used to compare two integers - any width, signed or unsigned.

I know that a basic macro that work can be written like this:

          #define min(x, y)   (x) < (y) ? (x) : (y)

But this involves side-effect of evaluating expressions 'x' and 'y' twice, which I don't want.

For robustness, expressions must be evaluated once only.

Till now, my approach seems like this:

          #define min(type, x, y)  ( {  \ 
                  type __tmp1 = (x);                      \
                  type __tmp2 = (y);                      \
                  __tmp1 < __tmp2 ? __tmp1 : __tmp2; } )

          int a, b, c;
          uint16_t p, q, r;

                   .
                   .
                   .

          c = min(int, a, b);

The C compiler throws error: "expecting ; found ( ", and many others.

How can I re-write this macro so that is usage take this form :

          <result> = min( <type>, <parm1>, <parm2> );

It seems that 'min' macro can be written so that its usage is:

           min( <result>, <type>, <parm1>, <parm2> );  

But it would be nice to have first form.

Update#1 on 2012-09-04:

Thank you guys, all the info provided in your answers/comments gave me a wider perspective of possibilities. Well, I am not using gcc, neither my compiler supports C11 spec, so the only options that seem to be available are:

  1. Use this form of macro:

           // min( <result>, <type>, <parm1>, <parm2> ); 
    
           #define min(result, type, x, y)  {                   \ 
                  type __tmp1 = (x);                      \
                  type __tmp2 = (y);                      \
                  result = __tmp1 < __tmp2 ? __tmp1 : __tmp2; } 
    
            int p, q, r;
                .
                .
                .
    
            min(r, int, p, q);
    
  2. The other approach is :

          inline char min_char(char x, char y)       { return x < y ? x : y; }
          inline short min_short(short x, short y)    { return x < y ? x : y; }
          inline int min_int(int x, int y)          { return x < y ? x : y; }
          inline long min_long(long x, long y)      { return x < y ? x : y; }
    
          inline unsigned char min_uchar(unsigned char x, unsigned char y)    { return x < y ? x : y; }  
          inline unsigned short min_ushort(unsigned short x, unsigned short y) { return x < y ? x : y; }   
          inline unsigned int min_uint(unsigned int x, unsigned int y)       { return x < y ? x : y; }  
          inline unsigned long min_ulong(unsigned long x, unsigned long y)   { return x < y ? x : y; }  
    
    
          #define   min(type, x, y)    min_##type(x, y)
    
    
          int p, q, r;
               .
               .
               .
    
          r = min(int, p, q);
    

Are there any side-effects of 2nd approach, that might yield unexpected results in some cases, especially regarding 'short' and 'char' types - signed or unsigned.

Any improvements or suggestions are welcome.

EDITED:

How will the user specify the below function:

            'min_uchar'

He/she must write:

             r = min(uchar, p, q);

Is there any other way to write the function 'uchar', so that user can simply write:

             r = min(unsigned char, p, q);

In this case I can't name the function as 'min_unsigned char', as it is not allowed in C. Is there any other way or user will have to specify type as 'uchar' instead of 'unsigned char' in macro 'min'.

Update on 2012-09-10:

Thank you all guys for your help. Since I need to accept an answer, I'm accepting Eitan T's answer, but I appreciate responses from all of you. Thanks.

jacks
  • 294
  • 3
  • 15
  • The macro looks OK to me other than being GCC-specific. I'd remove `r = `. With or without that, I can't reproduce the compiler error you report. http://ideone.com/h2Tjv – Steve Jessop Sep 04 '12 at 09:00
  • @SteveJessop: It seems there is a space after a ``\`` character (line 1). – md5 Sep 04 '12 at 09:02
  • @Kirilenko: good catch! I missed it because my text editor is configured to strip trailing whitespace on save. – Steve Jessop Sep 04 '12 at 09:05
  • @SteveJessop- sorry, `r = ` was a typo. I corrected it. – jacks Sep 04 '12 at 12:56
  • For your 2nd approach: I assume it's just a copy-and-paste error, but you need to give the different functions different names! – Steve Jessop Sep 04 '12 at 13:58
  • @SteveJessop- oops! typo again. I corrected it. See the update, named _edited_ section. – jacks Sep 04 '12 at 14:26

4 Answers4

3

Of course your macro can be independent of type specifier, this is one of the things that makes macros so powerful. You can either:

  1. Pass the variable name and the type and let the macro deal with the type.
  2. Pass the variable name without the type and assume that the macro performs legal operations on that variable, regardless of the type.

Your actual problem is that in the first form you expect your macro to return an expression, but inside it you declare variables and what-not. I believe that because of that, you put the curly braces in the macro, and now it expands to: ({ bla bla }), which would give you the following error message in ISO C99:

ISO C forbids braced-groups within expressions

Unfortunately, in ISO C99 you can't both have an expression AND declare temporary variables inside it. This is what functions are made for.

So either use the second form that you described, that is pass the "result" variable to the macro:

#define min(type_, x_, y_, result_)                    \
    do {                                               \
        type_ __tmp1 = (x_);                           \
        type_ __tmp2 = (y_);                           \
        result_ = (__tmp1 < __tmp2 ? __tmp1 : __tmp2); \
    } while(0)

or use an inline function instead.

P.S:
Also, this and this are worth reading for good practices when writing C macros.

Community
  • 1
  • 1
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • Thanks for useful info. Does it mean that, if I do not declare variables inside { ... }, then the result would be an expression in standard C? ie z = { x < y ? x : y } would be valid? – jacks Sep 04 '12 at 12:30
  • No, you need _round_ parentheses `()`. Curly braces `{}` do _not_ indicate an expression. – Eitan T Sep 04 '12 at 12:43
  • I'm not sure how this helps you in the end. Since you need to specify the exact type for each macro use, you might as well use explicit function calls for that specific type. Make it inline to avoid call overhead. You also have better/stricter type checking then. – Ioan Sep 11 '12 at 14:22
  • @Ioan I This macro is generic for all types, whereas inline functions need to be written separately for each type. – Eitan T Sep 11 '12 at 15:21
  • @EitanT I'll give you that. You don't have to copy/paste the function for each type, but that's hardly saving much to use a macro and forgo type checking. – Ioan Sep 11 '12 at 17:28
  • @Ioan Well, that's what the OP wanted. – Eitan T Sep 11 '12 at 17:34
2

If you're using gcc statement expressions, then you can also use the gcc extension keyword typeof (or __typeof__):

      #define min(x,y)  ( {                                \ 
              typeof(x) __tmp1 = (x);                      \
              typeof(y) __tmp2 = (y);                      \
              __tmp1 < __tmp2 ? __tmp1 : __tmp2; } )

C11 introduces type-generic expressions using the _Generic keyword:

int min_int(int x, int y) { return x < y ? x : y; }
long min_long(long x, long y) { return x < y ? x : y; }
#define min(x,y) _Generic((x + y),                        \
                          int: min_int,                   \
                          long: min_long)(x, y)

Given that you're willing to write the type in the macro invocation, you could use:

int min_int(int x, int y) { return x < y ? x : y; }
long min_long(long x, long y) { return x < y ? x : y; }
#define min(type,x,y) min_ ## type(x, y)

This is the only syntax that is valid in legacy versions of C.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Note that the questioner's macro converts both operands to a specified type, and compares them in that type (after integer promotion). Your macro compares them in whatever type they jointly get converted to by the usual arithmetic conversions. In the example in the question the operands are the same type, and the caller specifies that type, so this makes no difference. But the questioner's macro has the ability to explicitly control a mixed-type comparison, which arguably is an improvement on the C language ;-) – Steve Jessop Sep 04 '12 at 09:04
  • OP wants C89 or C99 compliant, so I guess the C11 part is irrelevant. Just sayin'. – Eitan T Sep 04 '12 at 09:34
  • Now that i think about it, OP wants _standard C_, so the first part is also irrelevant. – Eitan T Sep 04 '12 at 09:59
  • @EitanT yes, statement expressions are non-standard. See my update. – ecatmur Sep 04 '12 at 10:09
1

Macrofunctions cannot perform typecheck. If you want to operate on operands of a specified type (and force compilers warnings if the arguments have incompatible type), you have to use a function (maybe inline if you think about performances).

Your method is pleasing, but braced-groups with expressions are a gcc extension (not standard), so a standard compiler can't evaluate your macrofunction as an expression, which have a certain value.

Besides, you have a space after your \ character, which cause syntax error.

/* GCC-compatible */
#define min(t, x, y) ({ \
    t __tmp1 = (x); \
    t __tmp2 = (y); \
    __tmp1 < __tmp2 ? __tmp1 : __tmp2; \
})
md5
  • 23,373
  • 3
  • 44
  • 93
0

Since all solutions seem to require specifying type, you might as well call a specific macro to do the comparison. You can also generalize to just two macros and use the largest type for each of signed/unsigned:

#define smin(x_, y_, result_)                     \
  do {                                            \
    int64_t __tmp1 = (x_);                        \
    int64_t __tmp2 = (y_);                        \
    result_ = __tmp1 < __tmp2 ? __tmp1 : __tmp2;  \
  } while(0)
#define umin(x_, y_, result_)                     \
  do {                                            \
    uint64_t __tmp1 = (x_);                       \
    uint64_t __tmp2 = (y_);                       \
    result_ = __tmp1 < __tmp2 ? __tmp1 : __tmp2;  \
  } while(0)

Be sure to only compare types of the same signage.

Ioan
  • 2,382
  • 18
  • 32