Sams Teach Yourself C in 24 Hours (13 page)

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

When you finish writing a C program and start to compile it, you might get some error or warning messages. Don’t panic when you see error messages. We’re human beings.

Everybody makes mistakes. Actually, you should appreciate that your compiler catches some errors for you before you go any further.

Usually, your compiler can help you check the grammar — that is,
syntax
— of your C

program and make sure you’ve followed the C programming rules properly. For instance, if you forget to put the ending brace on the main() function in line 8 of Listing 2.1, you’ll get an error message something like this: syntax error : end of file found.

Also, the linker will issue an error message if it cannot find the missing code for a needed function in the libraries. For instance, if you misspell printf() as pprintf() in the program of Listing 2.1, you’ll see an error message: ‘_pprintf’: unresolved external (or something similar).

All errors found by the compiler and linker must be fixed before an executable file (binary code) can be made.

04 067231861x CH02 1/25/00 10:42 AM Page 37

Writing Your First C Program

37

Debugging Your Program

In the computer world, program errors are also called
bugs
. In many cases, your C compiler and linker do not find any errors in your program, but the result made by running the executable file of the program is not what you expect. In order to find those “hidden”

errors in your program, you may need to use a debugger.

Normally, your C compiler already includes a debugger software program. The debugger can execute your program one line at a time so that you can watch closely what’s going
2

on with the code in each line, or so that you can ask the debugger to stop running your program on any line. For more details about your debugger, refer to the instructions that come with your C compiler.

Later in this book, you’ll learn that debugging is a very necessary and important step in writing software programs. (This topic is covered in Hour 24, “Where Do You Go From Here.”)

Summary

In this lesson you learned the following concepts and statements about the C language:

• Some header files should be included at the beginning of your C program.

• Header files, such as stdio.h and stdlib.h, contain the declarations for functions used in your C program; for example, the printf() and exit() functions.

• Comments in your C programs are needed to help you in documenting your programs. You can put comments anywhere you like in your programs.

• In ANSI C, a comment starts with the opening comment mark, /*, and ends with the closing comment mark, */.

• Every C program must have one but only one main() function. The program execution starts and ends with the main() function.

• The return statement can be used to return a value to indicate to the operating system whether an error has occurred. The exit() function terminates a program; the argument to the function indicates the error status, too.

• Compiling and linking are consecutive steps that have to be finished before an executable file is produced.

• Everybody, including you and me, makes mistakes in programming. Debugging is a very important step in your program design and coding.

In the next lesson you’ll learn more about the essentials of C programs.

04 067231861x CH02 1/25/00 10:42 AM Page 38

38

Hour 2

Q&A

Q Why do you need to put comments into your programs?

A
Comments help you document what a program does. Especially when a program becomes very complex, you need to write comments to explain different parts in the program.

Q Why is the
main()
function needed in a program?

A
The execution of a C program starts and ends with the main() function. Without the main() function, the computer does not know where to start to run a program.

Q What does the
#include
directive do?

A
The #include directive is used to include header files that contain the declarations to the functions used in your C program. In other words, the #include directive tells the C preprocessor to look into the include path to find the specified header file.

Q Why do you need a linker?

A
After compiling, some function code may still be missing in the object file of a program. A linker must then be used to link the object file to the C standard library or other user-generated libraries and include the missing function code so that an executable file can be created.

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 D, “Answers to Quiz Questions and Exercises.”

Quiz

1. Can a C compiler see the comments within your C program?

2. What kind of files does a C compiler actually produce?

3. Does the exit() function return a value? What about the return statement?

4. What is a header file?

04 067231861x CH02 1/25/00 10:42 AM Page 39

Writing Your First C Program

39

Exercises

1. Is #include the same as #include “stdio.h”?

2. It’s time for you to write a program on your own. Referring to the program in Listing 2.1, write a C program that can print out a message: It’s fun to write my own program in C.

3. Update the program in Listing 2.1 by adding one more newline character into the message printed out by the printf() function. You should see two lines of the
2

message on the screen after running the updated executable file:

Howdy, neighbor!

This is my first C program.

4. What warning or error messages, if any, will you get when you’re compiling the following program?

#include

#include

main()

{

printf (“Howdy, neighbor! This is my first C program.\n”);

exit(0);

}

5. What error messages will you get for the following program when you’re trying to compile it?

void main()

{

printf (“Howdy, neighbor! This is my first C program.\n”);

return 0;

}

04 067231861x CH02 1/25/00 10:42 AM Page 40

05 067231861x CH03 4.10.2000 10:59 AM Page 41

HOUR 3

Learning the Structure of

a C Program

The whole is equal to the sum of its parts.

—Euclid

In Hour 2, “Writing Your First C Program,” you saw and wrote some simple C programs. You also learned about the basic structure of a C program. You know that a program written in C has to be compiled before it can be executed. In this lesson you’ll learn more essentials within a C program, such as

• Constants and variables

• Expressions

• Statements

• Statement blocks

• C function types and names

• Arguments to functions

• The body of a function

• Function calls

05 067231861x CH03 4.10.2000 10:59 AM Page 42

42

Hour 3

The Basics of a C Program

As a building is made of bricks, a C program is made of basic elements, such as expressions, statements, statement blocks, and function blocks. These elements are discussed in the following sections. But first, you need to learn two smaller but important elements, constant and variable, which make up expressions.

Constants and Variables

As its name implies, a
constant
is a value that never changes. A
variable
, on the other hand, can be used to present different values.

You can think of a constant as a music CD-ROM; the music saved in the CD-ROM is never changed. A variable is more like an audio cassette: You can always update the contents of the cassette by simply overwriting the old songs with new ones.

You can see many examples in which constants and variables are in the same statement.

For instance, consider the following:

i = 1;

where the symbol 1 is a constant because it always has the same value (1), and the symbol i is assigned the constant 1. In other words, i contains the value of 1 after the statement is executed. Later, if there is another statement,

i = 10;

after it is executed, i is assigned the value of 10. Because i can contain different values, it’s called a variable in the C language.

Expressions

An
expression
is a combination of constants, variables, and operators that are used to denote computations.

For instance, the following:

(2 + 3) * 10

is an expression that adds 2 and 3 first, and then multiplies the result of the addition by 10. (The final result of the expression is 50.)

Similarly, the expression 10 * (4 + 5) yields 90. The 80/4 expression results in 20.

Here are some other examples of expressions:

05 067231861x CH03 4.10.2000 10:59 AM Page 43

Learning the Structure of a C Program

43

Expression

Description

6

An expression of a constant.

i

An expression of a variable.

6 + i

An expression of a constant plus a variable.

exit(0)

An expression of a function call.

Operators

As you’ve seen, an expression can contain symbols such as +, *, and /. In the C language, these symbols are called
arithmetic operators
. Table 3.1 lists all the arithmetic operators and their meanings.

T

3

ABLE 3.1

C Arithmetic Operators

Symbol

Meaning

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Remainder (or modulus)

You might already be familiar with all the arithmetic operators, except the remainder (%) operator. % is used to obtain the remainder of the first operand divided by the second operand. For instance, the expression

6 % 4

yields a value of 2 because 4 goes into 6 once with a remainder of 2.

The remainder operator, %, is also called the
modulus operator
.

Among the arithmetic operators, the multiplication, division, and remainder operators have a higher precedence than the addition and subtraction operators. For example, the expression

2 + 3 * 10

yields 32, not 50, because of the higher precedence of the multiplication operator.

3 * 10 is calculated first, and then 2 is added into the result of the multiplication.

05 067231861x CH03 4.10.2000 10:59 AM Page 44

44

Hour 3

As you might know, you can put parentheses around an addition (or subtraction) to force the addition (or subtraction) to be performed before a multiplication, division, or modulus computation. For instance, the expression

(2 + 3) * 10

performs the addition of 2 and 3 first before it multiplies the result by 10.

Other operators, which are used for syntax, include the comma and semicolon. The semicolon is generally used to indicate the end of a statement, as you will see later. The comma is used in certain instances where a statement is comprised of a list of expressions or declarations.

You’ll learn more C language operators in Hours 6, “Manipulating Data,” and 8, “Using Conditional Operators.”

Identifiers

Along with numbers (such as the constant 7) and operators (such as the symbol +), expressions can also contain words that are called
identifiers
. Function names (such as exit) and variable names (such as i), as well as reserved keywords, are all
identifiers
in C.

The following is the set of characters you can use to make a valid identifier. Any characters or symbols that do not follow these rules are illegal to use in an identifier.

• Characters A through Z and a through z.

• Digit characters 0 through 9 (but these can not be used as the first character of an identifier).

• The underscore character (_).

For instance, stop_sign, Loop3, and _pause are all valid identifiers.

The following are illegal characters; that is, they do not meet the above set of rules for identifiers:

• C arithmetic signs (+, -, *, /).

• Period, or dot character (.).

• Apostrophes (‘) or quotes (“).

• Any other special symbols such as *, @, #, ?, and so on.

Some invalid identifiers, for example, are 4flags, sum-result, method*4, and what_size?.

05 067231861x CH03 4.10.2000 10:59 AM Page 45

Learning the Structure of a C Program

45

Never use the reserved keywords, or the names of the standard C library functions, for variable names or function names that you create in your own C programs.

Other books

School of Fortune by Amanda Brown
Here Comes Trouble by Anna J. Stewart
The Finder: A Novel by Colin Harrison
They'll Call It Treason by Jordon Greene
Run by Francine Pascal
The Face in the Frost by John Bellairs
Devil's Demise by Lee Cockburn