I have seen the following code on the Internet:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);
void setup()
{
mySerial.begin(9600);
Serial.begin(9600);
delay(100);
}
void loop()
{
if (Serial.available()>0)
mySerial.write(Serial.read());
if (mySerial.available()>0)
Serial.write(mySerial.read());
}
The command works perfectly fine. How was it possible in the code to write the command without ";" at the end of the line?
The link to the code is: enter link description here
-
3take a coding course or read a book about C or C++Juraj– Juraj ♦2018年11月16日 13:32:33 +00:00Commented Nov 16, 2018 at 13:32
1 Answer 1
Do you refer to this block?
if (Serial.available()>0) <- here
mySerial.write(Serial.read());
if (mySerial.available()>0) <- here
Serial.write(mySerial.read());
If so, there is a ;
at the end of each command. The commands are just split onto two lines each. It could be written like this:
if (Serial.available()>0) mySerial.write(Serial.read());
if (mySerial.available()>0) Serial.write(mySerial.read());
The second and fourth lines are the body of the if
. Better indenting with the original arrangement would be:
if (Serial.available()>0)
mySerial.write(Serial.read());
if (mySerial.available()>0)
Serial.write(mySerial.read());
Or even better, include the brackets around the body:
if (Serial.available()>0) {
mySerial.write(Serial.read());
}
if (mySerial.available()>0) {
Serial.write(mySerial.read());
}
-
So this means, we are allowed to neglect the {} and () for conditions, right? But why do sometimes errors occur if I do not write this symbols?Асмир Абдимажитов– Асмир Абдимажитов2018年11月16日 13:20:18 +00:00Commented Nov 16, 2018 at 13:20
-
2You can omit the brackets if there is only one statement in the body of the if.Majenko– Majenko2018年11月16日 13:45:27 +00:00Commented Nov 16, 2018 at 13:45
-
1A conditional or loop expression, such as 'if' or 'while', controls the next statement or block. It does not need its own semicolon because it is not a complete complete statement. A block is one or more statements surrounded by '{' and '}' and is treated like a statement. So the following simple statement ended with ';' or block surronded by '{', '}' is a necessary part of the 'if' or 'while'.JRobert– JRobert2018年11月17日 14:45:17 +00:00Commented Nov 17, 2018 at 14:45