Check if Block is null before executing? (macros)

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

  1. ArtOfWarfare macrumors G3


    Nov 26, 2007
    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:

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

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

    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

    Aug 9, 2009
    Sailing beyond the sunset
  3. ArtOfWarfare thread starter macrumors G3


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

    Oct 11, 2012
    "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

    Feb 2, 2008
    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.

Share This Page