Quicker if-statement: if `variable` is “value” or “value”

前端 未结 7 2110
感情败类
感情败类 2020-12-18 15:44

How can you compare against multiple possibilities in one argument?

Example:

if ((integer == 2) || (integer == 5))

if ((string == \"hello\") || (str         


        
7条回答
  •  北海茫月
    2020-12-18 16:18

    This isn't part of the language. If you really want to avoid the typing, you could just create a function to do it, something along the lines of:

    int intIsIn (int needle, int *haystack, size_t sz);
    :
    if (intIsIn (integer, {2,5}, 2)) ...
    

    (and similar for other data types). I question the usefulness of this approach however because (1) it's only less typing for longer lists; and (2) you'll probably end up on "The Daily WTF" :-)

    My opinion would be to just suck it up, it's not really that much typing.

提交回复
热议问题