I don't like this… Is this cheating the language?

前端 未结 15 2662
一向
一向 2021-02-13 15:52

I have seen something like the following a couple times... and I hate it. Is this basically \'cheating\' the language? Or.. would you consider this to be \'ok\' because the IsNu

15条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 16:28

    I don't think it's any different than something like this:

    INT* pNumber = GetAddressOfNumber();
    
    if ((pNUmber != NULL) && (*pNumber > 0))
    {
      // valid number, do whatever
    }
    else
    {
      // On a null pointer, it drops to here, because (pNumber != NULL) fails
      // However, (*pNumber > 0), if used by itself, would throw and exception when dereferencing NULL
    }
    

    It's just taking advantage of a feature in the language. This kind of idiom has been in common use, I think, since C started executing Boolean expressions in this manner (or whatever language did it first).)

提交回复
热议问题