2

Is there any way to define macro which can have one or zero parameters?

I need something to be used as in this example:

#define MY_RETURN(ret) return ret;

void foo(){
    MY_RETURN();
}

int foo_integer(){
    MY_RETURN(1);
}

I am not able to find solution for this.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mihalko
  • 563
  • 2
  • 5
  • 14
  • There are grounds for objecting to both possible duplicates. It depends in part how rigid the '0 or 1' argument requirement is. The solutions tend to allow '0 or more' arguments, rather than just '0 or 1'. – Jonathan Leffler Apr 18 '13 at 01:18

3 Answers3

2

In C99 and later, it is possible to use variadic macros.

C11 (n1570), § 6.10 Preprocessing directives

# define identifier lparen identifier-list , ... ) replacement-list new-line

Your macro may look something like:

#define MY_RETURN(...) return __VA_ARGS__

If you need to count arguments, you may check here for instance.

Community
  • 1
  • 1
md5
  • 23,373
  • 3
  • 44
  • 93
  • I was thinking about the same idea, unfortunatelly, I have to program it for DOS, using old Borland compiler. Are you sure your syntax is correct? If yes, I will mark this as an answer. – Mihalko Mar 06 '13 at 14:48
  • @Mihalko: Well, if your compiler does not support C99, you may check the extensions he offers. This syntax is correct, except (unfortunately) in C89. – md5 Mar 06 '13 at 14:51
  • Thank you. It is definitelly usefull information for compilers from these days :) – Mihalko Mar 06 '13 at 15:01
  • The `__VA_ARGS__` notation allows 2 and 3 and ... arguments equally as well as 0 or 1. This may or may not matter. – Jonathan Leffler Apr 18 '13 at 01:15
0

Define two MY_RETURN macros, one with parameter and one without! A kind of overloading, but for macros.

Christian
  • 1
  • 1
-1

Based on the answer of How to define macro function which support no input parameter and support also input parametr in the same time

Consider something like this:

#define MY_RETURN(ret) { \
  int args[] = {ret}; \
  if(sizeof(args) > 0) \
    return ret; \
}
Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268