Check if Block is null before executing? (macros)

Discussion in 'iOS Programming' started by ArtOfWarfare, May 20, 2014.

  1. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #1
    If you attempt to run a null block, your program crashes, so you need to wrap it in a check if it's null, like so:

    Code:
    if (block != nil) {
        block(arg);
    }
    I had a lot of different spots where I needed to do this kind of thing, so I ended up writing this macro:

    Code:
    #define CHECK_NULL_EXEC_BLOCK(BLOCK, ...) if (BLOCK != nil) BLOCK(__VA_ARGS__)
    And you use it like:

    Code:
    CHECK_NULL_EXEC_BLOCK(block, arg);
    My questions are:

    Does anyone see a problem with my macro? Is there some way it can be improved? I think it may not work with blocks which take no arguments at all - what's the best way I can modify it to handle that?

    Also, as some of you may be aware, I hate macros in C. They're not hygienic and lead to extremely frustrating to debug situations. But I don't think there's a way to write this without a macro... unless someone can think of that I didn't.
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
  3. ArtOfWarfare thread starter macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #3
    What is the significance of making it a static inline function as opposed to an ordinary function?
     
  4. MeFromHere macrumors 6502

    Joined:
    Oct 11, 2012
    #4
    "inline" should be clear; the compiler may put the function's body in the calling code instead of making a call to a real function. The program is (probably) faster and (probably) bigger when you use inline. This corresponds closely to the effect of the macro.

    "static" essentially hides the function definition from the linker, so its scope is only the file.
     
  5. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #5
    Here's some ideas for improvement, wether you agree it is or not is another matter. I tend to go for something simpler, like yourself for these. You could wrap the pointer in a parenthesis, not that it should ever be anything but a pointer but still.

    http://c.learncodethehardway.org/book/ex20.html
     

Share This Page