1

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!

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

2 Answers 2

1

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.

10
  • 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, 2017 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, 2017 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, 2017 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, 2017 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, 2017 at 11:46
-1

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.

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.