JKop said:
Will the following print "NOT equal" on all implementations:
#include <iostream>
signed main()
{
bool k;
k = 5;
std::cout << (k == 5 ? "equal" : "NOT equal");
}
In the above, you are converting integral type into a boolean type.
Focus on staying in the same domains, and don't cross them unless
necessary.
int main(void)
{
bool result = false;
int k = 5;
result = k == 8;
result = result && k == 5;
std::cout << "Result is " << result << endl;
return EXIT_SUCCESS;
}
In my experience, converting between bool and numerics is only
needed for storing objects and maybe accessing hardware. When
optimizing for space, boolean variables may be converted to
bits. Interchanging bools and integers is a dangerous
practice.
Let's say that a bool is 8-Bit on a particular implementation. When you
assign 5 to a bool, does the bool's bit pattern represent:
A) The integer 1
B) The integer 5
C) Implementation-defined ?
Why do we care?
If we use a bool variable for boolean results, we are not
concerned about its conversion to an integer and its integral
value.
We can easily convert boolean variables to bits. Heck, if
your going to convert from bool to integer, why not just
pack it and convert bool to bits? Why waste the extra
bits?
Are the following statments equivalent at all times:
k = true;
++k;
k = false;
--k;
Even if k had initially been set to 5?
-JKop
I wouldn't mix bools with integers, floats, or doubles.
Often times, mixing makes no sense and just makes the
program needlessly complex and difficult to maintain.
The Dogma:
1. Keep it simple, easy to read, understand and maintain.
2. Don't optimize until the project is finished or
out of resources.
3. Just because you are able to do something in a language
doesn't mean you should do it.
4. Focus on how to get the task completed, not on
how many different ways the language can be used.
5. Test early, test often.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book