If

From Microduino Wiki
Jump to: navigation, search

if(Conditional judgment statement)

if statement is used to test whether a condition is achieved with comparison operator. For example, if the digital input is higher than the specified value. The syntax of if statement is:

if (someVariable > 50)
{
  //execute some statements
}

This program is to test if the value of someVariable greater than 50. When it is, execute some statements. In another word, if only the outcome (named test expression)in the bracket behind if is true, execute the statements in brace(named execute the statement block);otherwise, skip the statements in the brace. The brace behind if statement can be omitted. If it is omitted, there is only one statement (end with a semicolon)becoming the execution statement.


if (x > 120){ 
  digitalWrite(LEDpin1, HIGH);
  digitalWrite(LEDpin2, HIGH); 
}                                 // keep this way of writing

Evaluation expressions in parentheses need the following operators:

Comparison operators:


 if(x == y)          //if x is equal to y
 if(x != y)          //if x isn’t equal to y
 if(x <  y)        //if x is less than y 
 if(x >  y)         //if x is greater than y
 if(x <= y)        //if x is less of equal to y
 if(x >= y)       //if x is greater of equal to y

Pay attention to the use of the assignment operator(like if (x = 10)): Single “=” represents the assignment operator, which is to set the value of x as 10(store 10 into x variable).Two “=” represents the comparison operators(like if (x == 10)), which is used to test whether x is equal to 10.

The latter is true only when x is 10 , and the former is forever true.

This is because the C operates if (x=10) according to the following rule:assign 10 to x(as long as the number of the assignment statement is not 0, it is always true), so the current value of x is 10.And at this time, the value of the if test expression is 10, and it is always true, because the non-zero value is true forever. So if (x = 10) will be always true, which is not the ideal outcome to run if. Besides, that x is assigned with 10 is also not the result what we are looking forward to.

Another branch condition control structure is if...else .

[Return to Arduino Syntax Manual]