Why is a true condition referred to as non zero?

Why is a true condition referred to as non zero?
Because C++ interprets every non zero value as true.
Because every non zero value cast to bool evaluates to true. That's how it is. I guess I could blabber something about assembly instructions to show that is makes sense, but there really is no point. Computers and programming languages are made by people. They have conventions in them, just like anything else. Deal with it.
(The C++ standard defines "false" as zero and "true" as "not false", so in other words, anything that is not zero is true.)
Casting!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;


class FedUpInt {
	int value;

 public:
	FedUpInt(int i = 0) : value(i) {}
	operator int() const { return value; }
	operator bool() const { return value == 0; }
};

ostream& operator<<(ostream &out, const FedUpInt &i) { return out << (int)i; }


int main() {
	int a = 5;
	FedUpInt b = 5;

	cout << a << " is " << (a ? "true" : "false") << endl;
	cout << b << " is " << (b ? "true" : "false") << endl;

	return 0;
}
5 is true
5 is false
Oh god oh man oh god oh man oh god oh man oh god, please don't do that lol
Yeah, as Intrexa says, don't use C-style casts please, line 15's C-Style cast will confuse beginners as to the correct way to cast.
Not even that, I don't evah want to deal with things that break 'the rules'. I don't want to have to know every niche thing about a class, because it has 1 bizarre non intuitive mechanic
The point Mathead200 was trying to make was that you can design your class however you want, but if you make it counter-intuitive then as you said it gets confusing.
Anon1010 wrote:
Why is a true condition referred to as non zero?

When you cast an int to a bool (whether it be implicit or explicit) it returns true iff the int != 0. That's just how the casting operation is defined for the intrinsic type int. That was my point; that's just how to C++ standard defined it. My class “FedUpInt” uses a Unix-style (shell-style) cast. (I know, shell doesn't actually cast data.) 0 meaning true, and non 0 meaning false. That's just how I (or I guess they) defined it.
No, as hamsterman said there is a completely different reason. Casting an int to a bool forces it to 0 or 1, but checking if an int is true does not.
Last edited on
Topic archived. No new replies allowed.