Why is assert a macro and not a function?

前端 未结 5 821
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 16:06

My lecturer has asked me that in class, and I was wondering why is it a macro instead of a function?

5条回答
  •  臣服心动
    2020-12-23 16:26

    Some assertions can be expensive to call. You've just written a high performance matrix inversion routine, and you add a sanity check

    assert(is_identity(matrix * inverse))
    

    to the end. Well, your matrices are pretty big, and if assert is a function, it would take a lot of time to do the computation before passing it into assert. Time you really don't want to spend if you're not doing debugging.

    Or maybe the assertion is relatively cheap, but it's contained in a very short function that will get called in an inner loop. Or other similar circumstances.

    By making assert a macro instead, you can eliminate the calculation entirely when assertions are turned off.

提交回复
热议问题