Does boolean true ever return 0? [duplicate] - c++

This question already has answers here:
Can I assume (bool)true == (int)1 for any C++ compiler?
(5 answers)
Closed 7 years ago.
I was in a lecture and on the power point slides states that true would return 0 and false would return 1. I stated that in Visual Studio anything non zero is considered true, but is there a C++ standard that defines 0 as true?
Visual studio's results were disregarded as non standard but I doubt that it is.
bool tru = true; // returns 0
bool fal = false; // returns 1

Absolutely not. From the C++14 working draft (chosen here because I was able to find it easily, not because it's specific to C++14):
A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.
— http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf §4.5.6 (page 85)
Indeed, this behavior is common to most programming languages. Off the top of my head, for instance, Perl, Python, PHP, and Javascript all treat 0 as false and nonzero values as true. The only situation I can think of where 0 is "true" is in UNIX shell scripting, where an exit code of 0 is used for success and nonzero values are used for errors.

As mentioned in the accepted answer here, true is defined by the standard to compare equal to 1, and false to 0:
(§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Related

Why is the return type of isdigit() int instead of boolean?

I was reading the cplusplus reference for the isdigit() function, where I got this,
int isdigit ( int c );
Return Value: A value different from zero (i.e., true) if indeed c is
a decimal digit. Zero (i.e., false) otherwise.
What does this term "different from zero" indicate, I mean why we can't just stick to 0 or 1.
Also when I tested this function, it is always returning either 1 or 0, then why simply documentation can't say that isdigit function returns 1, instead of saying "different from zero".
The reason is cross compatibility with C.
C itself didn't acquire a Boolean type until C99 and while that was over 20 years ago there's actually little justification for changing the definition of a widely used library function.
A explicit Boolean type has little practical advantage over the conventional use of 0 for false and non-zero for true other than readability.
By different from zero it means 'not zero'. It's near universal computing convention that when encoding Boolean values as numerical values 0 represents 'false' and all other values can be used to represent 'true'.
In general that's not something to worry about because constructs like if(isdigit(c)) will work because if() conforms to the same convention (in C and C++).
But if you're writing something like count+=isdigit(c) to perhaps count the number of digits in a string you may not get the answer you want.
As pointed out in the comments implementations may have reason for not returning 1 as true.

Why are `true` and `false` both considered variables?

I am new to C++ (and quite new to programming overall) and I was reading my C++ college book ("Starting out with C++ Early Objects" 9th edition by Gaddis, Walters and Muganda) when I came across a note on the bool data type.
"NOTE: Notice that true and false do not have quotation marks around them. This is because they are variables, not strings."
Now, from what I've learned, variables can be changed. I understand that a variable of the bool data type would be a variable, but how come true and false are considered variables?
From my understanding, false is stored as an integer value 0 and true as an integer value 1. I tried assigning values x where x is 0<x<0 to a bool and they all output 1 which made me come to the conclusion that true is also everything other than 0 (in other words, true is the same as !false?).
So if this is true, how come 'false' is considered a variable and not a constant?
You’re using a book that shows clear lack of understanding of the subject matter by the author. That book is lying to you. Throw it in the trash.
true and false are Boolean literals: they are a straightforward way of writing down a value of type bool. "true" and "false" are string literals – and, unfortunately, C++ can help you shoot yourself in the foot by converting them to their address, and then to a Boolean. So you get this wonderful nugget:
bool b1 = "false"; // string contents don’t matter
assert(b1 == true);
using book = bool;
book b2 = false;
assert(b2 == false);
The asserts are a way of writing true statements in the code: they mean that, at the point they appear, the condition in the parentheses must be true.
true and false are stored in whatever way the compiler desires – this is an implementation detail and the standard places no requirements here, other than true having to convert to 1 in numerical context, and false having to convert to 0 there. Usually they are not stored as integers, but bytes (char), i.e.
assert(sizeof(int) > sizeof(bool));

Why is a if-statement with comma-separated expressions allowed by Microsoft's C/C++ compiler? [duplicate]

This question already has answers here:
How does the Comma Operator work
(9 answers)
Closed 7 years ago.
I stumbled upon some syntactically weird looking code recently when porting a c++ project from Windows to Linux.
if ( isObjectNear( objectPos, objectLength ) + .025, 0.125 ) { ... }"
In this if-statement a parenthesis was misplaced causing the statement to consist of two expressions separated by the comma. The boolean "isObjectNear(..)" method had default parameters which allowed the call to be made using Microsoft's compiler despite the obvious mistake.
It was when building on Linux with GCC the problem was discovered giving the error message:
error: value computed is not used [-Werror=unused-value]
The code in my case is more interesting than relevant to the question and the following code serve the purpose of the question more clearly with the return-value in comments:
if ( true, 0.5 ) ... // returns true since 0.5 > 0 ( 0 == false)
if ( true, 0.0 ) ... // returns false
if ( 1.0, false ) ... // returns false
if ( true, false, false, ..., true ) ... // returns true
So back to the question "Why is a if-statement with comma-separated expressions allowed by Microsoft's C/C++ compiler?"
It is allowed because it's syntactically correct and a standard compliant compiler must accept it.
The GNU compiler guesses that throwing away the result of the left hand expression was not intentional and helpfully gives you a warning. You've told the compiler to treat warnings as errors. If you hadn't done so, it would be allowed by gcc too.
The standard does not require the compiler to give a diagnostic when the result of an expression is not used, and Microsoft may have chosen not to do so. Even in gcc, Wunused-value is not enabled even by Wall which suggests that it is considered an option that is likely to have many false-positives. I don't think this case is a false positive, though. It seems to me a clear programmer mistake.
Edit. Apparently msvc also issues a warning, as commented by Richard Crittenden.

VB6 and C++ boolean literals

I am learning C++. I come from a background of: .NET and VB6.
I am intrigued about what the following webpage says about booleans: http://msdn.microsoft.com/en-us/library/ff381404(v=vs.85).aspx i.e.
"Despite this definition of TRUE, however, most functions that return a BOOL type can return any non-zero value to indicate Boolean truth. Therefore, you should always write this:
// Right way.
BOOL result = SomeFunctionThatReturnsBoolean();
if (result)
{
...
}
"
Does this apply to VB6 as well i.e. is there a problem saying: If BooleanValue = True Then?
The Windows API was designed to be used from C programs. Which until C99 didn't have a bool type. And still doesn't completely, C99 was never implemented by the Microsoft compiler for example. So they had to come up with a workaround, one that's highly compatible with the way C compilers deal with logical values. An int where 0 is false and anything else is true. Thus the advice.
VB6 has a dedicated Boolean type and keywords for the literal values True and False so doesn't quite have the same problem. You can however still get into trouble with poorly written COM servers. The underlying integral value for True is -1, highly incompatible with many other languages' implementation of a logical boolean type. Including C. There's a good reason for VB6 being the oddball, its And and Or operators don't distinguish between a logical and a arithmetic and/or. By making True equal to -1 and False equal to 0 there is no difference. Trouble can arise when a COM server returns a 1 to indicate true instead of VARIANT_TRUE.
But most of all, writing If booleanVariable = True Then is just ugly and nails on the blackboard for many programmers. Just write If booleanVariable Then and be done with it.
Not in VB, no, as True/False are real boolean values. In C/C++ however, BOOL is just a #define of int, thus you can assign a BOOL variable any integer value (TRUE in C is a #define of 1 (usually) and FALSE a #define of 0).
If you want better overlap with your VB experience, use the bool datatype in C++ which uses actual true/false values.
EDIT: Of course, in VB you say If BooleanValue = TRUE. In C++, the equivalent is if (BooleanValue == true) (note the ==, which is a comparison operator, as opposed to = which is an assignment operator), but in C++ you can skip the == true comparison and just use if (BooleanValue).

What does double not (!!) used on a non-boolean variable do? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Double Negation in C++ code.
I am working with production code where I have run across statements like this a few times:
Class.func(!!notABool);
The first couple of times I dismissed it as a programmer quirk (maybe to emphasize that it is a conditional statement rather than a number being passed into func?) but I have run across several statements that use the above and now I am wondering whether it actually makes a difference or not. In most cases notABool is a number(int, float, double... I have seen all 3) My initial guess was that it is akin to typing:
Class.func((bool)notABool);
but I am not entirely sure?
Yes, functionally it is exactly the same as doing (bool) notABool.
By definition, in C++ language the operand of ! is implicitly converted to bool type, so !!notABool is really the same as !! (bool) notABool, i.e. the same as just (bool) notABool.
In C language the !! was a popular trick to "normalize" a non-1/0 value to 1/0 form. In C++ you can just do (bool) notABool. Or you can still use !!notABool if you so desire.
For primitive types, yes, it's essentially equivalent to:
!(notABool != 0)
which in turn is equivalent to:
(bool)notABool
For non-primitive types, it will be a compiler error, unless you've overloaded operator!, in which case, it might do anything.
It's a legacy idiom from C, where it meant "normalize to 0 or 1". I don't think there's a reason to use it in C++ other than habit.
It's converting BOOL (define for int) to c++ bool. BOOL is a define that in some cases for true can contain different integer values. So for example BOOL a = (BOOL)1; and BOOL b =(BOOL)2; both pass check for true. But if you'll try to compare you'll find that a not equals b. But after conversion !!a equals !!b.
(bool)notABoo - is not akin, because you'll convert type of variable byte still'll have different values. !! converts not only type but in some cases values too.