Monday, July 7, 2008

IF

Lesson 6.1

Making decisions.

At some point of your program, you will need to make a decision on what to do when a certain value is achieved or not achieved. By doing this in your program, you will be changing the program flow. In C, there are 3 way to make decision.


Usage:-

if (expression) statement 1 [else statement 2]


Statement 1 will only be executed if the expression is true (non 0).

And the optional else if specified will be executed if expression is false.


if () usage example.




Though the usage of { } is optional for a single statement following if or else, I recommend using it. Indentation of if() is recommended, so that it is easier to debug, understand the program flow and read the code.





The code above can be rewritten.



The end result will be the same. It up to your programming style.


Nested if()

Nested if() is nothing more that if within if within if….Good example is lesson 4 porgram v1. When any one if () is true, executes the code for it and exits the nested if(). But be careful. When using nested if() you have to adhere to PIC nesting limitation as to how many levels of nested calls you can make, which is as stated below:-

Maximum nested calls.

  • 8 calls for PIC12 family,
  • 8 calls for PIC16 family,
  • 31 calls for PIC18 family.

Example.


















As you can see, it can get quite complicated. And is usually the source of many errors. Proper indentation helps make the code more readable. But use with care. This is just a simple example.

2 comments:

9W2BSR said...

for multiple level if, I normally use switch/case syntax... much simpler and faster...

Anonymous said...

microchips for cats. While sketching such entities, they make effective use of materials.


www.happy-shop.co.uk