[3.4-RC] Macro problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PowerWyrm
    Prophet
    • Apr 2008
    • 2986

    [3.4-RC] Macro problem

    Just a little reminder for C devs: be careful when using macros evaluating variables more than once, because unwanted effects could occur. I've screwed myself more than once with such macros...

    Here's a good example from mon-spell.c:

    Code:
    inven_damage(p_ptr, re_ptr->gf, MIN(dam * randcalc(re_ptr->dam, 0, RANDOMISE), 300));
    The MIN macro is defined as:

    Code:
    #define MIN(a,b)    (((a) > (b))? (b)   : (a))
    So writing something like MIN(random, fixed) is actually (random > fixed? fixed: random).

    In the previous example, nothing can ensure you that the result will be lower than 300, since randcalc will be called twice, once to compare the result to 300 and once to return the result!

    The fix is simple:

    Code:
    int calcdam = dam * randcalc(re_ptr->dam, 0, RANDOMISE);
    inven_damage(p_ptr, re_ptr->gf, MIN(calcdam, 300));
    PWMAngband variant maintainer - check https://github.com/draconisPW/PWMAngband (or http://www.mangband.org/forum/viewforum.php?f=9) to learn more about this new variant!
  • Derakon
    Prophet
    • Dec 2009
    • 9022

    #2
    As noted in another thread, it'd probably be a good idea to write macro names in ALL_CAPS or some other distinguishing method. It won't guarantee that you won't make this mistake, but it should help remind you that you aren't making a normal function call.

    And of course, where possible macros should be replaced by function calls. I don't think even Angdroid needs the minor performance improvements macros get you.

    Comment

    • Patashu
      Knight
      • Jan 2008
      • 528

      #3
      Won't good compilers inline the kinds of functions you'd make macros in the first place?
      My Chiptune music, made in Famitracker: http://soundcloud.com/patashu

      Comment

      • Magnate
        Angband Devteam member
        • May 2007
        • 5110

        #4
        Looks like this ought to be my job, since PowerWyrm's example (and all the many ones like it) are my errors. It might explain quite a few things!

        Opened as #1668.
        "Been away so long I hardly knew the place, gee it's good to be back home" - The Beatles

        Comment

        Working...
        😀
        😂
        🥰
        😘
        🤢
        😎
        😞
        😡
        👍
        👎