Section 6g

Simple Branching


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Using the Branching Tools

Now that you have learned about logical operators and operations, you can move into changing the actions of your program while it is running, a condition called decision making or branching. This will significantly expand your ability to make your programs flexible and adaptable to differing conditions.

Using if

So far, you have learned about the data types you can use in C. You have also learned about how to write a program in English or your native language, and use functional abstraction to translate the problem from English to C. Finally, you have learned how to implement mathematical operations, as well as the basics of relational operators and logical statements.

Your next step is to take the data you have learned about and combine it with the relational operators and logical statements to provide your programs with the ability to take different program paths. The process is called decision making, and also often called branching with consideration for the analogy of taking different paths in the program, or selection with consideration for choosing or selecting from a number of program paths. As you know by now, a normal program starts at the beginning of its main function, and implements each statement in exactly the order it was typed into the program file; as you learned, this is called linear progression or sequence. The program will continue this one line at a time process until either the program ends, or it runs into a branching condition.

At the point of the branching condition, the program steps may continue from that point forward, or the next program step may be in another location in the program. You have already seen a form of this when you used the methods. Your program comes to the function line, and the function is said to be "called". The effect of this call is that the program steps are transferred down to where the function is defined, and the work is done there. When the function has completed its work, the program steps pick back up at the next line under the line on which the function was called, and goes on.

The same condition will occur due to branching. Observe the following code.

x = 5;

if( x > 10 )
{
// decision is not made here
printString( "The variable x is larger than 10" );
printEndline();
}

// program skips the decision block and moves on

// whether decision is made or not, this code is run
printString( "The variable x holds: " + x );
printEndline();

You can see that the program would choose to jump over the "Value is larger than ten" output statement, and go on to outputting the value of x. The term "jump" is actually used in some lower level programming languages to implement this process. Here is graphic you can look at before you go on however. This one addresses the path of the program in a simple line kind of process.

Image of branching action in lines

Notice that the program steps continue in order (i.e., one right after the other) until the branching process occurs. For the simple if statement, there are two things that can happen. If the if condition evaluates to true, the program will branch away from the normal set of steps (i.e., "up" as seen in the graphic above). If the if condition evaluates to false, the program will continue on its original path passing by the branching process. Also notice that for either condition, the program will return to the next steps following the decision making process. You will see some differences to this in later topics.

Now take a look at the form of a normal if statement operation. The code segment below presents the generalized format, and then the example used above.

Generalized standard form for using the if statement.

if( conditional or relational statement, i.e., "truth")
action taken if conditional statement is true

Specific example related to the action above.

if( x > 10 )
printString( "Value is larger than 10" );

Using curly braces

The above examples represent legal C usage of the if statement action. However, there is a way to make this better, and to have significantly fewer errors in your program code. To keep from having a variety of different problems later on, you would be very wise to implement one absolute rule: Always use curly braces after every if statement, as well as any other branching statements that will soon be introduced.

To make sense of this rule, consider the following.

It is standard practice to indent after every branching condition test. This is shown in the two examples above. However, the C programming language has made it possible to implement more than one statement as part of a conditional operation. This is done by using curly braces ("{" and "}"). As mentioned previously, curly braces allow a programmer to designate a segment of code as a block. There are other reasons to create blocks, but for purposes of this reference, the primary usage of blocks will be for branching operations.

Shown below is the same code segment demonstrated above, only this time using curly braces to denote the block of operations that will occur if the conditional test evaluates to true.

if( x > 10 )
{
printString( "Value is larger than 10" );
}

Code-wise, this is no different than the example shown above, except that it might be a little easier to read now that the action code is a little separated from the if statement, and showing more white space. However, it becomes more interesting if you have several things you want to implement after the conditional test.

Shown next is an example of multiple actions after the if test.

if( x > 10 )
{
printString( "Value is larger than 10" );
printEndline();

printString( "This value is too large to be used" );
printEndline();

printString( "x will be reset to 10" );
printEndline();

x = 10;
}

Using the curly braces as shown makes it very clear where the decision has been made, and what statements will be implemented if the conditional expression evaluates to true. As mentioned earlier, additional white space, the space between the letters horizontally and vertically means absolutely nothing to the C compiler, but it could mean the difference between clarity and confusion in your program. As mentioned previously, there are two main reasons for always using curly braces. The first is clarity and readability of your code. The second is a little more insidious.

Consider the original code segment presented.

if( x > 10 )
printString( "Value is larger than 10" );

You could certainly have written your program like this, and while it is not good programming, it is legal in the C programming language. However, sometimes you find that you need to modify your program, and you discover that you have to add in the other items shown above. Under this condition, it is very common for programmers to implement the following.

if( x > 10 )
printString( "Value is larger than 10" );
printEndline();

printString( "This value is too large to be used" );
printEndline();

printString( "x will be reset to 10" );
printEndline();

x = 10;

This looks really good. The indenting seems to help the clarity, and the code looks sharp. In fact, it looks too sharp. Most of the times you come back to try to debug your program, which now has a big bug in it, you are going to look at this code segment, and say to yourself, "Yep, that looks okay". It does look okay, but it does not work as it would appear to. In fact, the six subsequent statements after the "Value is larger . . ." statement will all be implemented no matter what decision is made in the if statement. This is because they are not affected by the if statement.

Needless to say, that is not what you meant to have happen. Only the first statement, or the first block, after the if statement will be implemented as part of the decision making process. The others are unaffected by that same if statement, and the three subsequent statements will be implemented every time, no matter what the decision. Pretty much everyone who doesn't use curly braces every time will make this mistake sooner or later.

However, maybe you are the one person who observes these things carefully, and will never make the mistake. Once again, you must consider the "real world" of software development where people will be coming in after you have written a program, and their job is to modify and/or update the program. Many times, the thing they are doing is exactly the problem; they are adding new lines or operations to your old code. If they have a block of code (i.e., with curly braces) to add it to, they will make no mistakes.

If they are working quickly, and throw in the extra lines under yours (i.e., without the curly braces), they will have added a bug to the program. Save yourself and your fellow programmers the trouble; always use curly braces under every branching statement no matter how simple the process might be. Your code will look better and work better.

Matching curly braces

There is one more tip to throw into this discussion. When using the curly braces to identify a block, many people type the branching statement, then they type the "open" curly brace, then they start typing the code that will be inside the block. Sometime later, they plan on putting the "close" curly brace at the end of their block of code. And then, well, most people forget to add that close curly brace. These are the people you will see scratching their head over some weird error messages that their compiler is giving them because they are missing one or more curly braces.

Very commonly, people who start curly braces and forget to end them are actually missing several of their curly braces, and can end up spending hours trying to figure out the problems with their programs. It is never worth wasting your time on chasing down curly braces when you could be working on a solution. The solution to this little problem is as easy as the code below. You have seen this previously in this reference but it is presented again for emphasis; this is an important activity.

Type your branching statement. This is your if statement for right now, but this applies to loops and other conditional statements later

There are few times in programming where you can say that you will never make a certain kind of mistake. If there were a time, this would be it. If you add both your open and close curly braces at the same time, you will never get the errors related to that problem, and you get the added benefit of having your indenting properly managed all the way through your program. As you will soon see, when you place one if statement inside the block of another, a process called nesting, you will be indenting more than just three spaces at a time. Placing the curly braces at their correct location from the beginning will keep you out of trouble as your programs grow in complexity.

Designing if statement operations

After having read about the concepts of decision making and branching, this is the first topic that puts you into the coding operations. As you have seen, this is not terribly difficult. However, branching can become complicated if you do not take the time to think through the logic.

When you are designing a decision-making operation (i.e., working through your Four/Six Step Programming Process), always separate the decision making itself from the branched operation. For example, in designing the operation mentioned earlier in this topic, consider the following.

// check for input value greater than 10

// display error message

// reset value to 10

As you can see, the decision-making action is on its own unique line, and the steps in the branched block are indented and placed independently on their own lines below. This supports: 1) one design line for each line of code, which is preferred, and 2) clarity as to which operations are the result of which decision-making processes.

Consider the following.

// if input value greater than 10, display error message and reset value to 10

While the text is reasonably clear here, you will not have the clear indication of which code operation goes on which line when you get to your coding step(s). Also, without the indenting, your design does not show any of the structure it should for decision-making operations, and clarity will probably be lost.

Another common mistake looks like the following.

// if inputVal > 10 (BAD, BAD, BAD)

// display error message

The problem with this is that you are already writing the code in the comment and eliminating the value of thinking through your solution. The idea of writing the solution in English is that you provide yourself the desired goal in a language you understand. If you start trying to write your solution in code while you are still thinking through the problem solving, you could make a mistake in the design process which of course you will then transfer into code when that time comes around. Important rule: Do not write code in comments. It is redundant and it defeats your problem solving process.

Wrapping up the simple action

The if statement is the easiest and simplest way to branch to the varying tasks in your program with dependence on the program data or conditions. While the if operation itself will never get more complicated, creating alternatives for the original test and actions will get a little more messy. This is not a problem as long as you use the design process first before you worry about what the code looks like. You will continue on to other topics after this one to see how that can work.

Watch this video for an overview of several of the concepts in this topic. There are also opportunities to follow along and write your own code.