-1

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

asked Nov 16, 2018 at 13:02
1
  • 3
    take a coding course or read a book about C or C++ Commented Nov 16, 2018 at 13:32

1 Answer 1

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());
}
answered Nov 16, 2018 at 13:05
3
  • 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? Commented Nov 16, 2018 at 13:20
  • 2
    You can omit the brackets if there is only one statement in the body of the if. Commented Nov 16, 2018 at 13:45
  • 1
    A 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'. Commented Nov 17, 2018 at 14:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.