2 ms·
>Do you owe anything if you have 0 apples? This phrasing shows the error even more starkly. No, you don't owe anything if you have 0 apples. If you use this
by logicallee 9y ago
>Do you owe anything if you have 0 apples?
This phrasing shows the error even more starkly. No, you don't owe anything if you have 0 apples. If you use this as a test, however, then you also either "don't owe" anything if you have -5 apples, or you do owe something if you have 5 apples. You simply can't use this as the test.
To put this into code directly based on the logic you say it's an analogy for:
numapples = 0;
// Do you owe anything if you have 0 apples?
if (!numapples) {
printf("I don't owe any apples.\n");
}
else {
printf("I owe some apples.\n");
}
This simply doesn't work. (Gives wrong result at 5 for example.)
The correct tests are, respectively:
numapples = 5;
// have no apples
if (numapples == 0) {
printf("I don't have or owe any apples.\n");
}
if (numapples < 0) {
printf("I owe some apples.\n");
}
if (numapples > 0) {
printf("I have some apples.\n");
}
There is another, subtler, reason for this. What is special about the value "0" here is that it's the default value - you're born without any apples, or something.
But by making someone write the test like this:
(currentapples - startingapples) == 0
you can test whether there is any offset from a different starting value. The "0 == false" version of the test completely breaks that: it applies when you're testing an offset at 0, but breaks anywhere else. In other words as an offset it's equivalent to:
( currentapples == zeroapples ) && (zeroapples == 0)
don't get me wrong, I use it in code. But I'm not under the misapprehension that there is a real-world analogy. There isn't one. It's simply the definition of C/C++.
Whenever I see == 0 in an if test, I feel free to remove those 4 characters, don't get me wrong. Because it's just the definition of C. Not because I think there's any analogy with anything.
That said, which version of this code is cleaner and less likely to allow a programmer to make a logical mistake:
1.
if ((currentapples - startingapples) != 0) {
2.
if (currentapples - startingapples) {
to me, the intent of 1 is super-clear, as for the intent of 2, who knows, but of course after half of a second I can parse what its effect is, by running through the definition of C in my head. That's not great for reading and debugging programs. :)