I am new to C and In the loop part of an Arduino sketch if I make a list of "if" statements the script compiles, runs and works. But I have a feeling that after the first if statement the following ones should be "else if" statements. Is the second method more efficient? and could there be problems just using "if" statements.
It depends, both versions have their place. Post the code you're worried about.
A list of ifs is kinda' like "here try all of these, do the ones that are true." A block of if-else ifs is kinda like "Try these, only do the first one that is true. Skip the rest."
-jim lee
Perhaps:
A = 0
loop
if a == 0 do stuff : a++
if a == 1 do stuff : a++
would do the first, then the second action
A = 0
loop
if a == 0 do stuff : a++
elseif a == 1 do stuff : a++
would do the first, then NEXT TIME through the loop, it would do the second.
There is a shortcut for a stack of 'if-else-if' where all are testing the same integer value against a bunch of constants:
int VAR;
if (VAR == 3)
{
// Do stuff for 3
}
else if (VAR == 17)
{
// Do stuff for 17
}
else if (VAR == 5)
{
// Do stuff for 5
}
else
{
// Do stuff for no match
}
The shortcut is the 'switch/case' statement:
int VAR;
switch (VAR)
{
case 3:
// Do stuff for 3
break;
case 17;
// Do stuff for 17
break;
case 5:
// Do stuff for 5
break;
default:
// Do stuff for no match
break;
}
This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.