Hi.
I'm testing an Arduino clone called Moteino and when I look at some examples on how to program it I find some if/then statements without the curly braces {}.
I though this was an error on the code but when I run the compiler on it, it gives me no errors.
How come?
As far as the compiler is concerned, you only need braces if you want to execute several lines of code contingent on the if. So this is fine:
if(x<0)
x++;
Later, if you decide that something else needs to be executed there, you'll have to remember to add the braces to get more than one statement controlled by the if. To avoid the problems that occur if you forget, many people use braces with every if, whether they are strictly necessary or not.
thiyagarajanmb:
If it is "if" without curly braces, it means the "if" is applicable only the current next line. i.e.
if(you == 0)
int i = 10;
int k = 20;
In the above code,
int i = 10;
will only belong to if loop.
int k=20;
will not belong to the if loop.
If you want both in your loop, then you need braces, In other words, If the <mark>"If" statements is more than one line you need to have braces.</mark>
if (TRANSMITPERIOD == 0) TRANSMITPERIOD = 1000;
Serial.print("\nChanging delay to ");
Serial.print(TRANSMITPERIOD);
So in the above code, for instance, TRANSMITPERIOD = 1000 is executed if the if (TRANSMITPERIOD == 0) test is true, but Serial.print("\nChanging delay to ") and Serial.print(TRANSMITPERIOD), do not depend on the if test and are always executed. If TRANSMITPERIOD is 0 it will be changed to 1000 otherwise it will be whatever value it had before the if test. Correct?
Correct, and your indenting illustrates the issue with omitting the braces. Running your eye down the code, you'll be led to think that the serial prints are controlled by the if when in fact, they're not.
Putting the statement that is controlled by the if on the same line isn't helping either.
In C a statement is either one of the simple statements such as assignment, or
a compound statement like if or while, or its a brace-delimited list of statements.
Anywhere you can use a statement you can use any statement type including { ... }
Hence:
if (foo)
bar () ; // simple statement
if (foo)
; // null statement
if (foo)
while (bar) // while statement
baz () ;
if (foo)
while (bar)
{
...
}
if (foo)
{
while (bar)
{
..
}
}
The "gotcha" in this is cases like this:
if (foo)
if (bar)
one() ;
else
two () ;
if (foo)
if (bar)
one() ;
else
two () ;
They are the same code, but do you know which if the else matches? This
is known as a "dangling else" and good style requires using braces here to
make the intent clear (the compiler has its own unambigous idea of how to
read this, the human reader is easily confused though)