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 Answers 2
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.
-
1But 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– Jot2017年07月09日 11:13:29 +00:00Commented 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– Majenko2017年07月09日 11:15:11 +00:00Commented Jul 9, 2017 at 11:15
-
1In 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– Jot2017年07月09日 11:39:43 +00:00Commented Jul 9, 2017 at 11:39
-
1Personal opinions don't count. C and C++ are what they are. If you don't like it then program in visual basic.Majenko– Majenko2017年07月09日 11:40:53 +00:00Commented Jul 9, 2017 at 11:40
-
2
if( x ){
in C/C++ reads "if x is not equal to zero". Ifx
is numeric, that expression could be considered an idiomatic shorthand. Ifx
represents a boolean, it reads quite naturally. Consider, f/ex, the character-class testisdigit()
. Most people (in my experience) writeif( isdigit(x) ){
, notif( 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– JRobert2017年07月09日 11:46:29 +00:00Commented Jul 9, 2017 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.
IF
norserial
orAvailable
exist.