Negativ number as true in C++.
-
Till now, I have known that any positiv integer is true.
And any non positiv integer and the zero are false.Yeasterday I programmed a condition and I was surprised that negative integer is true too...
Therefore, I tried to search this definition in the C++ standard but I have found nothing about this...
-
[quote author="Zlatomir" date="1360325618"]Quote from C++ 2003 revision:
bq. 4.12 Boolean conversions [conv.bool]
... A zero value, null pointer value, or null member pointer value is converted to false; any
other value is converted to true.[/quote]Yeeeeeeessssss!
This was what I have searched :)Thank you very much!
-
[quote author="broadpeak" date="1360324319"]Till now, I have known that any positiv integer is true.
And any non positiv integer and the zero are false.
[/quote]Think more in "binary" oder "hexadeciamal" mode ;)
There are no difference between positiv or negativ, because you cannot set a minus before a hexadecimal value :)for an if clause, the "if" only see the binary or hexadecimal value.
Like
[code] if(0x80) { ...
[/code]That could be a signed (-1 I think...) or unsigned char (127), but for the if clause, it is true :)
-
[quote author="Serenity" date="1360326276"]
[quote author="broadpeak" date="1360324319"]Till now, I have known that any positiv integer is true.
And any non positiv integer and the zero are false.
[/quote]Think more in "binary" oder "hexadeciamal" mode ;)
There are no difference between positiv or negativ, because you cannot set a minus before a hexadecimal value :)for an if clause, the "if" only see the binary or hexadecimal value.
Like
[code] if(0x80) { ...
[/code]That could be a signed (-1 I think...) or unsigned char (127), but for the if clause, it is true :)
[/quote]
Ok, I understand. Thanks!
-
The explanations of this are very good. As far back as I can remember expressions evaluate as "true" when they are non-zero. In the *nix world, most functions returned 0 for success and negative for the error condition. M$ complicates this even more by making tokens to denote the system, error code, etc. Hence the need for the macro SUCCESS in a lot of their return values.
It is always a good practice, for readability and no ambiguity, to just put:
if (value == 0) or
if (value != 0)and just let the compiler optimize it out.
-
[quote author="Serenity" date="1360326276"]
Think more in "binary" oder "hexadeciamal" mode ;)
There are no difference between positiv or negativ, because you cannot set a minus before a hexadecimal value :)[/quote]
Well... you can actually :) Hex is just a notation, it doesn't change the underlying bit meaning which can signify a negative integer. It's ok to do @int a = -0x1;@ , it's just not the typical use of it.This is a historic optimization. CPUs have a special instruction for checking 0 values (like jnz in assembly), so it was (no longer true of course for quite some time) cheaper to treat "anything but zero" as true.