Sams Teach Yourself C in 24 Hours (31 page)

BOOK: Sams Teach Yourself C in 24 Hours
9.49Mb size Format: txt, pdf, ePub
ads

If nothing else, you should know what a goto statement is so that you can properly cringe when you see one in somebody else’s code.

13 067231861x CH10 4.10.2000 11:02 AM Page 169

Controlling Program Flow

169

The following is the general form of the goto statement:

labelname:

statement1;

statement2;

.

.

.

goto labelname;

Here labelname is a label name that tells the goto statement where to jump. You have to place labelname in two places: One is at the place where the goto statement is going to jump (note that a colon must follow the label name), and the other is the place following the goto keyword.

The label for the goto statement to jump to can appear either before or after the statement.

10

One of the best things about C is that it encourages
structured programming
. Programs should act predictably and their behavior should be reasonably evident from merely reading over the source code.

Of course, one of the other best things about C is that the language itself does not enforce this ideal. It is left up to you, the programmer, to use the tools you are given to write clean, elegant, readable, structured code.

In this chapter we have seen the break, continue, and goto statements.

The improper use of these branching statements can lead to what is known as “spaghetti code.” (If you printed out the source code and drew arrows on the page to indicate the flow of execution, you would end up with a

drawing of spaghetti.) When a program’s execution jumps around in unpredictable ways, it makes it very difficult (or for a large, complex project, often nearly impossible) to determine the intended or actual behavior of a program.

The use of the goto statement can easily lead to spaghetti code, especially if it is used to jump backwards, or jump out of flow-control statements. When you see a random label just sitting there in the code, you know only that some other code is going to jump there using goto — you just don’t know when, or why, without stopping to search the rest of the function.

The effects of the continue statement, at least, are limited to the looping statement where it is used. However, complex loops can be hard to decipher unless you know exactly when and why the loop will terminate.

The same goes for break. Aside from switch statements, it can be used to jump out of for, while, or do-while loops. Generally, this should only be used to break out of an infinite loop. Otherwise, use your conditional

expression to terminate the loop.

13 067231861x CH10 4.10.2000 11:02 AM Page 170

170

Hour 10

Summary

In this lesson you learned the following important statements and keywords for conditional branching and looping in C:

• An important task of a program is to instruct the computer to jump to different portions of the code according to the specified branch conditions.

• The if statement is a very important statement for conditional branching in C.

• The if statement can be nested for making a series of related decisions in your program.

• The if-else statement is an expansion of the if statement.

• The switch statement helps you to keep your program more readable when there are more than just a couple of related decisions to be made in your code.

• The case keyword, followed by a colon and an integral constant value, is used as a label in the switch statement. The default: label is used at the end of a switch statement when no case applies to the condition.

• The break statement can be used to exit the switch construct or a loop (usually, an infinite loop).

• The continue statement is used to let you stay within a loop while skipping over some statements.

• The goto statement is to enable the computer to jump to some other spot in your code. Using this statement is not recommended because it may make your program unreliable and hard to debug.

In the next lesson you’ll learn about a very important concept—pointers.

Q&A

Q How many expressions are there in the
if
statement?

A
The if statement takes only one expression to hold the conditional criteria. When the expression evaluates to a nonzero value (that is, the conditions are met), the statements controlled by the if statement are executed. Otherwise, these statements are skipped and the next statement following the if statement block is executed.

Q Why is the
if-else
statement an expansion of the
if
statement?

A
When the conditional expression in the if statement evaluates to a value of zero, the program control flow is returned back to the original track. However, when the conditional expression in the if-else statement evaluates to zero, the program control flow branches to the statement block under the else keyword and returns 13 067231861x CH10 4.10.2000 11:02 AM Page 171

Controlling Program Flow

171

to its original track after the statements controlled by else are executed. In other words, the if statement allows a single statement block to be executed or skipped entirely, whereas the if-else statement executes one of the two statement blocks under the control of the if-else statement.

Q Why do you normally need to add the
break
statement into the
switch
statement?

A
When one of the cases within the switch statement is selected, the program control will branch to the case and execute all statements within the selected case and the rest of the cases that follow it. Therefore, you might get more results than you expected. To tell the computer to execute only the statements inside a selected case, you can put a break statement at the end of the case so that the program control flow will exit the switch construct after the statements within the case are executed.

10

Q What can the
continue
statement do inside a loop?

A
When the continue statement inside a loop is executed, the program control is branched to the end of the loop so that the controlling while or for statement can be executed and another iteration can be started if the conditional expression still holds. Inside the loop, any statements following the continue statement will be skipped over each time the continue statement is executed.

Workshop

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix B, “Answers to Quiz Questions and Exercises.”

Quiz

1. Given x = 0, will the arithmetic operations inside the following if statement be performed?

if (x != 0)

y = 123 / x + 456;

2. Given x = 4, y = 2, and operator = ‘-’, what is the final value of x after the following switch statement is executed?

switch (operator){

case ‘+’: x += y;

case ‘-’: x -= y;

case ‘*’: x *= y;

13 067231861x CH10 4.10.2000 11:02 AM Page 172

172

Hour 10

case ‘/’: x /= y;

default: break;

}

3. Similar to question 2, using x = 4, y = 2, and operator = ‘-’, what is the final value of x after the following switch statement is executed?

switch (operator){

case ‘+’: x += y; break;

case ‘-’: x -= y; break;

case ‘*’: x *= y; break;

case ‘/’: x /= y; break;

default: break;

}

4. What is the value of the integer variable x after the following code is executed?

x = 1;

for (i=2; i<10; i++){

if (i%3 == 0)

continue;

x += i;

}

Exercises

1. Rewrite the program in Listing 10.1. This time, use the logical expression i%6 ==

0 in the if statement.

2. Rewrite the program in Listing 10.1 by using nested if statements.

3. Write a program to read characters from the standard I/O. If the characters are A, B, and C, display their numeric values on the screen. (The switch statement is required.)

4. Write a program that keeps reading characters from the standard input until the character q is entered.

5. Rewrite the program in Listing 10.7. This time, instead of skipping 3 and 5, skip the integer that can be evenly divided by both 2 and 3.

14 067231861x pt 3 1/25/00 10:44 AM Page 173

PART III

Pointers and Arrays

Hour

11 Understanding Pointers

12 Understanding Arrays

13 Manipulating Strings

14 Understanding Scope and Storage Classes

14 067231861x pt 3 1/25/00 10:44 AM Page 174

15 067231861x CH11 1/25/00 10:16 AM Page 175

HOUR 11

Understanding Pointers

The duties of the Pointer were to point out, by calling their names, those in
the congregation who should take note of some point made in the sermon.

—H. B. Otis, Simple Truth

You’ve learned about many important C data types, operators, functions, and loops in the past 10 hours. In this lesson you’ll learn about one of the most important and powerful features in C: pointers. The topics covered in this hour are

• Pointer variables

• Memory addresses

• The concept of indirection

• Declaring a pointer

• The address-of operator

• The dereference operator

More examples of applying pointers will be demonstrated in the next several hours of the book, especially in Hour 16, “Applying Pointers.”

15 067231861x CH11 1/25/00 10:16 AM Page 176

176

Hour 11

What Is a Pointer?

Understanding pointers is vital to being an effective C programmer. Until now, you have only dealt with variables directly, by assigning values to them. This hour introduces a new concept, known as
indirection
.

Instead of assigning values directly to variables, you can indirectly manipulate a variable by creating a variable called a
pointer
, which contains the memory address of another variable.

So, why is this so important? For starters, using the memory address of your data is often the quickest and simplest way to access it. There are many things that are difficult, if not outright impossible, to do without pointers, such as dynamically allocating memory, passing large data structures between functions, even talking to your computer’s hardware.

In fact, you have already used a pointer — in Hour 1, of this book “Taking the First Step”! Do you remember the string “Howdy, neighbor! This is my first C

program.\n”? A string is actually an array, which is itself a kind of pointer.

There is a lot more discussion later on in this book about arrays, memory allocation, and the wonderful things you can do with pointers. For now, the first step is to understand what a pointer is, and how to work with one in your programs.

From the definition of a pointer, you know two things: first, that a pointer is a variable, so you can assign different values to a pointer variable, and second, that the value contained by a pointer must be an address that indicates the location of another variable in the memory. That’s why a pointer is also called an
address variable
.

Address (Left Value) Versus Content (Right

Value)

As you might know, the memory inside your computer is used to hold the binary code of your program, which consists of statements and data, as well as the binary code of the operating system on your machine.

Each memory location must have a unique address so that the computer can read from or write to the memory location without any confusion. This is similar to the concept that each house in a city must have a unique address.

When a variable is declared, a piece of unused memory will be reserved for the variable, and the unique address to the memory will be associated with the name of the variable. The address associated with the variable name is usually called the
left value
of the variable.

BOOK: Sams Teach Yourself C in 24 Hours
9.49Mb size Format: txt, pdf, ePub
ads

Other books

Streetlights Like Fireworks by Pandolfe, David
Tails and Teapots by Misa Izanaki
The Bachelorette Party by Karen McCullah Lutz
Covenant With the Vampire by Jeanne Kalogridis
The Queen's Consort by Leia Rice
Blood Lure by Nevada Barr
Ridin' Dirty: An Outlaw Author Anthology (OAMC Book 1) by Blue Remy, Kim Jones, MariaLisa deMora, Alana Sapphire, Kathleen Kelly, Geri Glenn, Winter Travers, Candace Blevins, Nicole James, K. Renee, Gwendolyn Grace, Colbie Kay, Shyla Colt
A Bona Fide Gold Digger by Allison Hobbs


readsbookonline.com Copyright 2016 - 2024