Is anybody using the named boolean operators?

前端 未结 13 2127
南方客
南方客 2020-12-06 10:52

Or are we all sticking to our taught \"&&, ||, !\" way?

Any thoughts in why we should use one or the other?

I\'m just wondering because several answe

相关标签:
13条回答
  • 2020-12-06 11:12

    "What's in a name? That which we call &&, || or ! By any other name would smell as sweet."

    In other words, natural depends on what you are used to.

    0 讨论(0)
  • 2020-12-06 11:12

    It's nice to use 'em in Eclipse+gcc, as they are highlighted. But then, the code doesn't compile with some compilers :-(

    0 讨论(0)
  • 2020-12-06 11:15

    In cases where I program with names directly mapped to the real world, I tend to use 'and' and 'or', for example:

    if(isMale or isBoy and age < 40){}
    
    0 讨论(0)
  • 2020-12-06 11:21

    Using these operators is harmful. Notice that and and or are logical operators whereas the similar-looking xor is a bitwise operator. Thus, arguments to and and or are normalized to 0 and 1, whereas those to xor aren't.

    Imagine something like

        char *p, *q; // Set somehow
        if(p and q) { ... } // Both non-NULL
        if(p or q) { ... } // At least one non-NULL
        if(p xor q) { ... } // Exactly one non-NULL
    

    Bzzzt, you have a bug. In the last case you're testing whether at least one of the bits in the pointers is different, which probably isn't what you thought you were doing because then you would have written p != q.

    This example is not hypothetical. I was working together with a student one time and he was fond of these literate operators. His code failed every now and then for reasons that he couldn't explain. When he asked me, I could zero in on the problem because I knew that C++ doesn't have a logical xor operator, and that line struck me as very odd.

    BTW the way to write a logical xor in C++ is

    !a != !b
    
    0 讨论(0)
  • 2020-12-06 11:22

    I like the idea of the not operator because it is more visible than the ! operator. For example:

    if (!foo.bar()) { ... }
    
    if (not foo.bar()) { ... }
    

    I suggest that the second one is more visible and readable. I don't think the same argument necessarily applies to the and and or forms, though.

    0 讨论(0)
  • 2020-12-06 11:22

    So to summarize: it's not used a lot because of following combination

    • old code where it was not used
    • habit (more standard)
    • taste (more math-like)

    Thanks for your thoughts

    0 讨论(0)
提交回复
热议问题