Function-like macro

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Richard Bos

    #16
    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

    Comment

    • pete

      #17
      Re: Function-like macro

      Richard Bos wrote:
      [color=blue]
      > #define A_FROM_B(b) ((b)<10? (b): 2*(b))
      >
      > Note the parens around b in the definition of the macro.
      > They will save
      > your bacon some day when you decide to call A_FROM_B(x+10).[/color]

      Trivia point:
      Only the first and last pair are needed for bacon saving.

      #define A_FROM_B(b) ((b) < 10 ? b : 2 * (b))

      ? b :
      means the same thing as
      ?(b):

      --
      pete

      Comment

      • Richard Bos

        #18
        Re: Function-like macro

        pete <pfiland@mindsp ring.com> wrote:
        [color=blue]
        > Richard Bos wrote:
        >[color=green]
        > > #define A_FROM_B(b) ((b)<10? (b): 2*(b))
        > >
        > > Note the parens around b in the definition of the macro.
        > > They will save
        > > your bacon some day when you decide to call A_FROM_B(x+10).[/color]
        >
        > Trivia point:
        > Only the first and last pair are needed for bacon saving.
        >
        > #define A_FROM_B(b) ((b) < 10 ? b : 2 * (b))
        >
        > ? b :
        > means the same thing as
        > ?(b):[/color]

        In this case, perhaps. Howsoever, I'd advise getting into the habit of
        parenthesisisin g anyway, for psychobabblical reasons.

        Richard

        Comment

        Working...