Arduino if else: How to use the Arduino 'if-else' statement, and use its different forms in your code - long form and compact. Learn about the ternary operator (?) for ultra-compact conditional operation.

The Arduino if else statement :

  • Or how the Arduino makes decisions.

  • Learn exactly how to write the "if else" code.

  • Find out the different ways of using it - you don't  always need the 'else' part.

  • Find out the short way of writing 'if-else' (less brackets to write).

  • learn about the extremely cryptic, but extremely compact  C conditional statement '? :' - that's not a typo '?' it is a command set! 

The if-else statement allows your program to make decisions based on the outcome of an expression. It is a standard language construct in C and C++, and for that matter standard in most programming languages.

In most non c-like languages there is usually an if-then-else explicitly stated (and sometimes an 'endif'). In C/C++, 'then' and 'endif' statements are implied.

Pseudo code if then else

In pseudo code you have to write the THEN part otherwise the operation that you code will perform does not make sense. For example:


IF A == 10 THEN c = 0 d = 44 ELSE c = 1 d = 2; ENDIF
Note: Pseudo code is code written in human readable form but not matching any programming language. It allows you to write down an algorithm (and think about it!) without worrying about syntax of the language you will later use.

Pseudo code operation

The above pseudo code is fairly obvious:

The conditional test comes between the IF and THEN statements.
If the result of the test is true, statements between THEN and ELSE are executed.
If the result of the test is false, statements between ELSE and ENDIF are executed.

Brackets and Braces

The above pseudo code can be translated to C as follows:

The expression is contained in the initial brackets (smooth brackets or parenthesis) and blocks of code are contained in curly brackets.

The curly brackets define the 'THEN', 'ELSE. and 'ENDIF' sections:


if (A == 10) <THEN> { c = 0; d = 44; } else <ELSE> { c = 1; d = 2; } <ENDIF>

Removing the pseudo code markers, results in the final c code form:


if (A == 10) { c = 0; d = 44; } else { c = 1; d = 2; }

Simpler if else layout

The curly brackets define blocks of code that are executed together. You can simplify the Arduino "if else" expression if there is only one instruction for a block (terminated in a semi-colon) by excluding the brackets:


if (A == 10) c = 0; else c = 1;

...and you can even put it all on one line for super-compact code:


if (A == 10) c = 0; else c = 1;

Arduino if statement without else

It is also valid to write an if statement without the else part:


if (A == 10) c = 0;

In this case only the when the expression is true will c be set to zero. If the expression is false then no other action is taken.

Chaining Arduino if else statements

Complex conditional code

Another C construct that you can use is the "else if" code. This allows you to nest conditional statements one after another. For example you might want to test a character to perform some action when found.

You could write:


if (ch == 'd') { Serial.println("data"); command = 1; } else if (ch == 'b') { Serial.println("begin"); command = 2; }

 
The code above always checks for the character 'd' first, followed by checking for the character 'b'. Of course you could write each if statement separately and the result would be the same. But, if you know that the letter 'b' will  be detected more often then the program is faster with chained if else statements.

If you write them separately then all the if statements must be executed regardless off which character is found i.e. wasting processing time.

You can chain these statements forever, but the Arduino case statement is better choice if you have to do lots of tests (as it is more compact). There can also be a problem in compiling huge nested if else code...

Problem with chained Arduino if else

The Arduino compiler will complain if you have too much code in the code blocks and a very large amount of chained if else statements (or it might fail to compile with an odd error message) - because a machine code jump statement can only jump a specific relative address space value and the large code size means a larger relative jump value.

The compiler could always use a long jump instruction but would be inefficient for most code (there is probably a compiler optimization switch that will force long jumps - but then every jump would be long increasing the code size).

If you find the compiler giving up, then the solution is to take the 'large' code blocks and place them into separate functions to reduce the jump distance. This is code factoring i.e. splitting complex parts into smaller blocks. It also makes the code easier to read and understand.

TIP: Factor code for the compiler to process chains of Arduino if else code.

For example the trivial code above could be re-written as:


static
int command=0; void d_action(void) { Serial.println("data"); command = 1; } void b_action(void) { Serial.println("begin"); command = 2; } void loop(void) { char ch; if ( Serial.available() ) ch = Serial.read(); if (ch == 'd') { d_action(); } else if (ch == 'b') { b_action(); } }

After rewriting the code you usually have to define variables used in the original "if else" block of code as static, as shown, so that all functions in the file can access the variables. See the 'command' variable for an example.


Note: Change variables to local file static to allow the same operation.

Here's that cryptic command set '? :'

It is called a ternary operator. This is the syntax:

<condition> ? <statement that executes on true> : <statement that executes on false>;

It works in exactly the same way as the if-else statement but the only difference is that both the false part and the true part must be present. It returns the result of the <true expression statement> if the condition is true and vice versa.

The reason you may want to use it, other than to write very unreadable code is to make code more compact.

Here is an example of generating different message output depending on a variable. Here it is used to show the results of connecting to an I2C chip.

    Serial.print("MCP4725 ");
    Serial.println(mcp4725.testConnection() ? F("Success") : F("Failed") );

Depending on the initialisation result, you will get 'Success' or 'Failed' output to the serial terminal.

The equivalent long-form if-else code is:

    Serial.print("MCP4725 ");
    if (mcp4725.testConnection() )
        Serial.println( F("Success") )
    else
        Serial.println( F("Failed") )

You can see that the first code is ultra compact but far less readable (unless you are used to it)!

Conclusions

The if-else statement is fundamental to letting your code make decisions and is very flexible (e.g. allowing you to leave off the else statement or use the short form). It allows any expression that evaluates to a Boolean in the conditional test part of the statement and it allows your program to make multiple, complex, decision based operations.

The short form 'ternary operator' can make extremely compact code but it should be used sparingly as it can be difficult to read.

If you have lots of different tests, and need a compact way of writing them, then the Arduino switch case C construct is very useful.


Comments

Have your say about what you just read! Leave me a comment in the box below.

Don’t see the comments box? Log in to your Facebook account, give Facebook consent, then return to this page and refresh it.



Privacy Policy | Contact | About Me

Site Map | Terms of Use