is there a pragmatic reason to use “if (0 == p) ” instead of “if (!p)”?

后端 未结 12 745
难免孤独
难免孤独 2021-02-05 06:18

I\'m inclined to write if statements by using logical negation operator:

if (!p)
    some_code();

Some people around me tend to use explicit co

12条回答
  •  既然无缘
    2021-02-05 07:08

    Personally, I'm a bit bored of the implicit conversion from int to boolean. I don't think it adds much to the C language any more. In C89 where there's no boolean type it's perfectly reasonable to use an integer as a boolean, in which case the conversion leads to good-looking code. I see why it can't be removed, especially when dealing with libraries that for compatibility reasons can't be changed to return boolean now there is one. But I certainly don't think it should be used in all cases.

    Sometimes, a 0 integer value means "there isn't one", but sometimes it means "there is one and it's zero". So I'm happy with:

    users = get_number_of_users();
    if (users) {
        // there are users
        ...
    } else {
        // there aren't users
    }
    

    I'm not at all keen on:

    length = strlen(ptr);
    if (length) {
        // there is length? OK, sort of...
    } else {
        // there isn't length? No, wait, there *is* a length, that length is 0
    }
    

    So there's your pragmatic reason to write if (length == 0) in preference to if (!length). "If not length" makes no sense in English, so isn't necessarily what you should be writing in code either.

    Admittedly, 0 was invented as a special place-holder to mean "there aren't any". But the realization that in many contexts it could be treated as a number like any other was an important breakthrough in the history of mathematics, and I don't think we should discard that just because C provides us with a syntax to treat it specially again ;-) If you want to know whether a number is 5, you compare it with 5, and normally I think the same should hold for 0.

提交回复
热议问题