If in C language, the simplest of Control Flow

If in C language, the simplest of Control Flow

It is the simplest decision instruction of all. Is true (1) or false (0)? The use of if is widespread and it's the best way to start with decision making, also known as Control Flow. Check out also this post about the other instructions for decision making in the C programming language.

https://www.techzorro.com/en/blog/control-flow-c/

Sample of Questions

Depending on the environment where the program in executing, the question could be similar to these:.

  • Was a button pressed?
  • Has a parameter changed?
  • Turn on the light?
  • Is the motor on?

Syntax

if

if consists in 3 parts: the word if itself at the start, the condition (between parenthesis) and the statement with a semicolon at the end. The condition is the question(s) asked and the statement is the action taken after the result of the questions is known.

if (condition) statement;

The previous line of code is used if the statement can be written in only 1 line of code. If it requires more lines, then it can be written the following way:

if (condition) {
  statement 1;
  statement 2;
  statement 3;
  statement 4;
  //etc
}

else

When the if condition is false, then the code will execute the code that follows else.

if (condition) { 
  //if the condition is TRUE, 
  //then this code will be executed.
  //
}
else {
  //if the condition is FALSE, 
  //then this code will be executed.
  //
}

Relational Operators

How to find out the result of the condition? You have to ask the correct question. The following relational operators will return a true (1) or false (0) depending in the condition.

  • Equal ==.
  • Not equal !=
  • Greater than >
  • Less than <
  • Greater than or equal >=
  • Less than or equal <=

For example:

if (A==B) statement //If A is equal to B, then the statement will be executed.
if (A>B) statement //If A is greater than B, then the statement will be executed.
  

Example of IF and ELSE

The following example is done for 8-bit microcontrollers and its programmed in MPlab X IDE.

In this code, I'm checking whenever buttons are pressed. If the button PORTBbits.RB0 remains unpressed, the result of checking it will return a 1. On the contrary, if it gets pressed, then the result will be 0. The statement is to turn a LED located on pin PORTBbits.RB2. The code for this action is:

if (PORTBbits.RB0==0) PORTBbits.RB2=1;

Other way to express this is using the admiration sign. It will return the same result.

if (!PORTBbits.RB0) PORTBbits.RB2=1;

techZorro's Index of Content

Keep Reading!

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.