I am very new to Arduino and I have a question I would like to clarify on Serial.Available()

According to Arduino documentation, Available() returns the number of bytes that are stored in the buffer, ready to be read. Why then, both If function below works, when there are data in the buffer? For Scenario A, it appears to me that there is no conditional statement, how then, would the IF function evaluates to TRUE?

Scenario A: IF(Serial.Available())

compare with

Scenario B: IF(Serial.Available()>0)

Thanks in advance!

  • Mind the case: neither IF nor serial or Available exist. – Edgar Bonet Jul 9 '17 at 11:19
  • the do the same thing; the 2nd is a pedantic long-hand way of writing it more explicitly – dandavis Jul 10 '17 at 20:51

In C, 0 is false and anything else is true. So if Serial.available() returns 0 it is considered false. If it returns 7, 23, 44, etc it is considered true.

| improve this answer | |
  • 1
    But it is bad programming. It should be "if(Serial.available()>0)". The Serial.available does not return a boolean, but an integer. Therefor it should be tested against an integer. Off-topic: was there something with 'bool' and 'boolean' ? – Jot Jul 9 '17 at 11:13
  • @jot Boolean doesn't actually exist. There's a typedef in C++ (and in "stdbool.h" for C) that links it to an unsigned char. 0 is false, anything not 0 is true. There is absolutely nothing "bad" about it. – Majenko Jul 9 '17 at 11:15
  • 1
    In my opinion an integer should be treated as an integer. Trying to be smart and rely on the compiler to fix bad programming is not okay. I think the 'boolean' and 'bool' problem have been fixed: "bool x = (bool) 23;" sets x to 1 and the same for boolean. – Jot Jul 9 '17 at 11:39
  • 1
    Personal opinions don't count. C and C++ are what they are. If you don't like it then program in visual basic. – Majenko Jul 9 '17 at 11:40
  • 2
    if( x ){ in C/C++ reads "if x is not equal to zero". If x is numeric, that expression could be considered an idiomatic shorthand. If x represents a boolean, it reads quite naturally. Consider, f/ex, the character-class test isdigit(). Most people (in my experience) write if( isdigit(x) ){, not if( isdigit(x) != 0 ){; even though the latter states in explicit detail, what test is to be made. It comes to stylistic preference, and like discussions of which programming editor is "best", & what placement of braces or indentation is "best", rapidly devolves into a religious argument. – JRobert Jul 9 '17 at 11:46

Scenario A, it appears to me that there is no conditional statement, h

The first is a test on if available() returns a non zero value.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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