I'm having the hardest time understanding how to use boolean operators such as NOT (!), AND (&&), and OR (||).
The books and tutorials always put examples with 1 and 0 in the statements which relate to true and false but, I'd like to be able to understand how these operators work with other values or variables such as text, as in login information, and numbers other than 1 and 0.
For example:
if (password = hello) then
or
if (password ! hello) then
are these correct? Is this how the operators are used?
int myvar = 5;
if(!myvar); // this would be false
if(myvar == 0); // same as above line -- false
myvar = 0;
if(!myvar); // now this is true
if(myvar == 0); // true
&& and || are to check multiple conditions at once:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int foo = 5;
int bar = 5;
if((foo == 5) && (bar == 5))
{
// executes if foo is 5 AND bar is 5
// if either are not 5, then the if condition is false and this block is not executed
}
if((foo == 5) || (bar == 5))
{
// executes if foo is 5 OR bar is 5
// if neither are 5, then the if condition is false and this block is not executed.
}
Would compare what the condition in the if statement needs to be, to the current value or state of the int/bool/string or whatever. Meanwhile using just = would set the value? That is the way i have been taught anyway...
Also when using (||)/(&&) i cannot get it to work as Disch has put it, i need to do if(foo == 5 || bar == 5) ... maybe it is just the compiler i am using, but try Disch's code first.
Also when using (||)/(&&) i cannot get it to work as Disch has put it, i need to do if(foo == 5 || bar == 5)
What about it doesn't work?
My code is exactly the same, I just put parenthesis around the individual comparisons to clarify so there's no ambiguitiy when it comes to operator precedence.
Yea works fine for me now, sorry it was a fault of my own.. The if statement was the same format but it was throwing up an error the other day and i couldn't figure it out. I just changed the statement in my current project and it works fine. Sorry about that. And thanks for clearing up the !/==0. I have kinda been fast-tracked in c++ on my college course and trying to learn as much as i can outside of educational establishments too. Have a keen interest in programming.
My fault, sorry about that... Works fine as Disch has put it.
Thanks Disch. I'm just starting to learn C++. I have Dev-C++ for my coding along with Visual C++. Getting into the boolean was a bit rough but, seeing it this way makes more sense.