Re: Function-like macro
Dale Hagglund <dale.hagglund@ gmail.com> wrote:
[color=blue]
> Others have already pointed out that you're probably much better off
> using an inline function. It's more easily readable and editable.
> That said, GCC does have a non-standard extension that allows you to
> do what you want:
>
> #define A_FROM_B(b) \
> ({ \
> int __b = (b); \
> int __a; \
> if (__b < 10) \
> __a = __b; \
> else \
> __a = 2*__b; \
> __a; \
> })[/color]
[color=blue]
> * I introduced the __b variable to prevent multiple evaluation
> of b. (Functions get you this for free, of course.)[/color]
Unfortunately it also makes the macro non-portable, since all
identifiers starting with __ (or _ plus capital letter) are reserved for
the implementation. __b is simple enough that it could clash with
something defined in a system header.
[color=blue]
> * As I mentioned, as far as I know this is non-standard.[/color]
'tis.
[color=blue]
> * Because macros are based on textual substitution, it's a
> good idea to introduce local variable names that aren't
> likely to collide with names used inside the macro
> arguments. (Again, functions completely avoid this issue.)[/color]
But make sure they're yours to use.
Richard
Dale Hagglund <dale.hagglund@ gmail.com> wrote:
[color=blue]
> Others have already pointed out that you're probably much better off
> using an inline function. It's more easily readable and editable.
> That said, GCC does have a non-standard extension that allows you to
> do what you want:
>
> #define A_FROM_B(b) \
> ({ \
> int __b = (b); \
> int __a; \
> if (__b < 10) \
> __a = __b; \
> else \
> __a = 2*__b; \
> __a; \
> })[/color]
[color=blue]
> * I introduced the __b variable to prevent multiple evaluation
> of b. (Functions get you this for free, of course.)[/color]
Unfortunately it also makes the macro non-portable, since all
identifiers starting with __ (or _ plus capital letter) are reserved for
the implementation. __b is simple enough that it could clash with
something defined in a system header.
[color=blue]
> * As I mentioned, as far as I know this is non-standard.[/color]
'tis.
[color=blue]
> * Because macros are based on textual substitution, it's a
> good idea to introduce local variable names that aren't
> likely to collide with names used inside the macro
> arguments. (Again, functions completely avoid this issue.)[/color]
But make sure they're yours to use.
Richard
Comment