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.

C

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:

C

else

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

C

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:

C

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:

C

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

C

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.

Juditova

Variable Frequency Drives: how this controller can transform induction motors forever

Juditova         Juditova        
Variable Frequency Drives: how this controller can transform induction motors forever           Variable Frequency Drives: how this controller can transform induction motors forever          
Back 15 seconds
Forward 60 seconds
more
    Back 15 seconds
    Forward 60 seconds
    Currently Playing