# logical AND...OR

• 02-14-2005
Chaplin27
logical AND...OR
Hey everyone,
SO I was making this test program just to work with classes and whatnot...and I was making a class for a Pen that has a member function WriteOnPaper(string write)...I have the function check the ink level of the pen and whether the index of the string is equal to the length of the word passed as a parameter:
Code:

```int length = write.length() - 1; int index = 0; while (m_InkLevel != 0 && index != length) {   cout << write[tick++];   m_InkLevel -= 1; }```
Ok...so I know this works...but prior to doing this I was using the Logical OR because in my head I was thinking whichever of the 2 conditions is reached I want the loop to end...YET I learned through much experimentation that AND is the way to go...which seems counterintuitive to me...doesnt AND mean when both conditions are true? So if the ink dries up before the word is fully written out I want it to end out...hmmm ok, phrasing it like that I understand why AND works...yet I'm not exactly sure why OR does not...is it because the only way it would break the loop is if in the rare occasion that both fail at the same time? Something like that?
I think it's an issue of how I word the code in my head when I type it out that has me thinking out the conditions wrong or something...
Sorry this is partially just me rambling and partially seeking answers...any ideas on how to approach writing out conditions with the cond.operators from a wording perspective? I thought the AND through and that pretty much makes sense, it's more the OR that I'm having a problem with...thanks a lot for listening to this mess haha :confused: } Chap
• 02-14-2005
Kaelin
With AND, both expressions MUST equal true. If EITHER ONE fails, the whole thing will fail.

With OR, either one of the expressions must be true. Therefore, if one fails, one is still true and it will still work.

You are saying

Code:

`(m_InkLevel != 0 && index != length)`
Which means

"So long as we still have ink ***AND*** we haven't reached the end, continue"

If you were to say

Code:

`(m_InkLevel != 0 || index != length)`
This is like saying,

"So long as we at least either have some ink or are not at the end of the file".

You need BOTH, hence AND.
• 02-14-2005
hk_mp5kpdw
These are equivalent:

Code:

`while( m_InkLevel != 0 && index != length)`
and

Code:

`while( !(m_InkLevel == 0 || index == length) )`
So...

A NOT_EQ B AND C NOT_EQ D

Is the same as:

NOT(A EQ B OR C EQ D)

Maybe the OR you were thinking of needing was the result of you wanting to write the second version above? Just a thought.