-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

closed as off-topic by Juraj, sempaiscuba, per1234, gre_gor, Roberto Lo Giacco Nov 21 '18 at 1:26

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Arduino, within the scope defined in the help center." – Juraj, sempaiscuba, per1234, gre_gor, Roberto Lo Giacco
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    take a coding course or read a book about C or C++ – Juraj Nov 16 '18 at 13:32
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? – Асмир Абдимажитов Nov 16 '18 at 13:20
  • 2
    You can omit the brackets if there is only one statement in the body of the if. – Majenko Nov 16 '18 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'. – JRobert Nov 17 '18 at 14:45

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