cplusplus
.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
Tutorials
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs
Forum
Beginners
Is it ok to assume 0 is false and 1 is t
Is it ok to assume 0 is false and 1 is true?
Nov 17, 2015 at 12:16pm UTC
anarelle
(68)
I've seen code where a condition is evaluated based on an int variable instead of bool.
1
2
3
4
int
condition cin >> condition;
if
(!condition)
//do something
I know that C++ supports that 0 is false and 1 is true, but is this safe code? Is it supported by all C++ compilers as a standard?
Could it also be a bad practice considering that you might switch to another language and find out that this kind of code isn't supported?
Nov 17, 2015 at 12:32pm UTC
coder777
(8444)
but is this safe code?
Yes.
Is it supported by all C++ compilers as a standard?
Yes.
The point is that 0 is false and all other numbers (negative as well as positive) are true.
Could it also be a bad practice considering that you might switch to another language and find out that this kind of code isn't supported?
If you switch to another language you will find that much more is not supported. But who knows, it depends on the other language.
Nov 17, 2015 at 12:33pm UTC
JLBorges
(13770)
> Is it supported by all C++ compilers as a standard?
Yes.
In a boolean context, zero is
false
, non-zero is
true
;
null pointer or pointer to member is
false
, non-null pointer or pointer to member is
true
.
In an integer context,
true
is 1,
false
is 0.
Topic archived. No new replies allowed.