0

I want to skip all '\r' and '\n' chars and I have IF statment:

char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting 
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

VS

char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting 
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

What is better and what is the difference?

3 Answers 3

4

Think about it "logically" (pun intended...):

You read a character. Say it's "A". You then compare it to both '\r' and '\n'.

char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting 
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR or A is not LF then add it". Since it's A and not LF or CR then it's going to add it. Now imagine it's CR. "If CR is not CR or CR is not LF then add it". CR is CR, so the first part will be false. But CR isn't LF, so the second part is true. If it's OR, then if either part is true then it will be true. So since CR is not LF it will add it.

Now:

char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting 
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR and A is not LF then add it". Since it's A and not LF or CR then it's going to add it. Now imagine it's CR. "If CR is not CR and CR is not LF then add it". CR is CR, so the first part will be false. But CR isn't LF, so the second part is true. Just as before. However, if it's AMD, then if BOTH parts are true then it will be true. So since CR is CR it won't add it.

In summary, the first one will ALWAYS be true since one half is always going to be true. The second one will ONLY be true if BOTH parts are true. So the first one just plain isn't going to do what you want.

1
  • Thanks for this. Just needed someone explain this :) My head is overflowed...
    – Martynas
    Commented Jun 26, 2015 at 13:20
1

You can rewrite first condition to be more obvious

if (c != '\r' || c != '\n') {

as

if (!(c == '\r' && c == '\n')) {

Which is always true (c have only one value), i.e. it makes no sense.

0

|| means logical OR

&& means logical AND

1
  • Thanks, i know the meaning. I want to know the difference and which one is better in this situation. My head is not working properly at the moment;)
    – Martynas
    Commented Jun 26, 2015 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.