Sams Teach Yourself C in 24 Hours (14 page)

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

You’ve already seen the return keyword in the previous hour. Hour 4, “Understanding Data Types and Keywords,” lists all of the reserved keywords.

Statements

In the C language, a
statement
is a complete instruction, ending with a semicolon. In many cases, you can turn an expression into a statement by simply adding a semicolon at the end of the expression.

3

For instance, the following:

i = 1;

is a statement. You might have already figured out that the statement consists of an expression of i = 1 and a semicolon (;).

Here are some other examples of statements:

i = (2 + 3) * 10;

i = 2 + 3 * 10;

j = 6 % 4;

k = i + j;

Also, in the first lesson of this book you learned statements such as

return 0;

exit(0);

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

Statement Blocks

A group of statements can form a
statement block
that starts with an opening brace ({) and ends with a closing brace (}). A statement block is treated as a single statement by the C compiler.

For instance, the following:

for(. . .) {

s3 = s1 + s2;

mul = s3 * c;

remainder = sum % c;

}

05 067231861x CH03 4.10.2000 10:59 AM Page 46

46

Hour 3

is a statement block that starts with { and ends with }. Here for is a keyword in C that determines the statement block. The for keyword is discussed in Hour 7, “Working with Loops.”

A statement block provides a way to group one or more statements together as a single statement. Many C keywords can only control one statement. If you want to put more than one statement under the control of a C keyword, you can add those statements into a statement block so that the block is considered as one statement by the C keyword.

Anatomy of a C Function

Functions are the building blocks of C programs. Besides the standard C library functions, you can also use some other functions made by you or another programmer in your C program. In Hour 2 you saw the main() function, as well as two C library functions, printf() and exit(). Now, let’s have a closer look at functions.

As shown in Figure 3.1, a function consists of six parts: the function type, the function name, arguments to the function, the opening brace, the function body, and the closing brace.

FIGURE 3.1

Function

Function

Argument List

The anatomy of a func-

Type

Name

to Function

tion in the C language.

int integer_add (int x, int y)

{

Start of Function

int result;

result = x + y;

Function Body

return result;

}

End of Function Body

and Function

The six parts of a function are explained in the following sections.

Determining a Function’s Type

The
function type
is used to signify what type of value a function is going to return after its execution. In Hour 2 for instance, you learned that the default function type of main() is int.

In C, int is used as the keyword for the integer data type. In the next hour, you’ll learn more about data types.

05 067231861x CH03 4.10.2000 10:59 AM Page 47

Learning the Structure of a C Program

47

Besides the int type, a function type can be one of the other types, such as the character type (keyword: char), the floating type (float), and so on. You will learn more about those types later in this book.

When you call a C function which returns a data type, the value it returns (
return value
) can then be used in an expression. You can assign it to a variable, such as int a = func();

or use it in an expression, like this

a = func() + 7;

Giving a Function a Valid Name

A
function name
is normally given in such a way that it reflects what the function can
3

do. For instance, the name of the printf() function means “print formatted data.”

Since a function name is an identifier, when creating your own functions you must follow the rules for creating valid identifiers when naming your function.

In addition, you cannot use the names of standard C functions such as printf() or exit() to name your own functions. They are already defined, and it is illegal to use the same function name in defining more than one function.

Passing Arguments to C Functions

Functions are useful because you can call them over and over from different points in your program. However it’s likely that you call a certain function for a slightly different reason each time.

For example, in Listing 2.1 in Hour 2, a character string, “Howdy, neighbor! This is my first C program.\n”, is passed to the printf() function, and then printf() prints the string on the screen. The entire purpose of printf() is to print a string on the screen, but each time you call it, you pass the specific string that you want it to print this time around.

Pieces of information passed to functions are known as
arguments
. As you’ve seen, the argument of a function is placed between the parentheses that immediately follow the function name.

The number of arguments to a function is determined by the declaration of the function, which in turn is determined by the task the function is going to perform. If a function needs more than one argument, arguments passed to the function must be separated by commas; these arguments are considered an
argument list
.

05 067231861x CH03 4.10.2000 10:59 AM Page 48

48

Hour 3

If no information needs to be passed to a function, you just leave the argument field between the parentheses blank. For instance, the main() function in Listing 2.1 of Hour 2 has no argument, so the field between the parentheses following the function name is empty. See the copy of Listing 3.1 below:

LISTING 3.1
.

A Simple C Program.

1: /* 02L01.c: This is my first C program */

2: #include

3:

4: main()

5: {

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

7: return 0;

8: }

The Beginning and End of a Function

As you might have already figured out, braces are used to mark the beginning and end of a function. The
opening brace
({) signifies the start of a function body, whereas the
closing brace
(}) marks the end of the function body.

As mentioned earlier, the braces are also used to mark the beginning and end of a statement block. You can think of it as a natural extension to use braces with functions because a function consists of one or several statements.

The Function Body

The
function body
in a function is the place that contains variable declarations and other C statements. The task of a function is accomplished by executing the statements inside the function body one at a time.

It is important to remember that any variable declarations must be placed at the beginning of the function body. It is illegal to put variable declarations anywhere other than the very beginning of a statement block.

If your function body contains variable declarations, they must all be placed first, before any other statements.

Listing 3.2 demonstrates a function that adds two integers specified by its arguments and returns the result of the addition.

05 067231861x CH03 4.10.2000 10:59 AM Page 49

Learning the Structure of a C Program

49

LISTING 3.2

A Function that Adds Two Integers

1: /* 03L01.c: This function adds two integers and returns the result */

2: int integer_add( int x, int y )

3: {

4: int result;

5: result = x + y;

6: return result;

7: }

As you learned in Hour 2, line 1 of Listing 3.1 is a comment that describes what
ANALYSIS
the function can do.

In line 2, you see that the int data type is prefixed prior to the function name. Here int is used as the function type, which signifies that an integer is returned by the function.

3

The function name shown in line 2 is integer_add. The argument list contains two arguments, int x and int y, in line 2, where the int data type specifies that the two arguments are both integers.

Line 3 contains the opening brace ({) that marks the start of the function.

The function body is in lines 4–6 in Listing 3.1. Line 4 gives the variable declaration of result, and is specified by the int data type as an integer. The statement in line 5 adds the two integers represented by x and y and assigns the computation result to the result variable. The return statement in line 6 then returns the computation result represented by result.

Last, but not least, the closing brace (}) in line 7 is used to close the function.

When you create a function in your C program, don’t assign the function too much work. If a function has too much to do, it will be very difficult to write and debug. If you have a complex programming project, break it into smaller pieces. Try your best to make sure that each function has just one task to do.

Making Function Calls

Based on what you’ve learned so far, you can write a C program that calls the integer_add() function to calculate an addition and then print out the result on the screen. An example of such a program is demonstrated in Listing 3.3.

05 067231861x CH03 4.10.2000 10:59 AM Page 50

50

Hour 3

LISTING 3.3

A C Program that Calculates an Addition and Prints the Result to the

Screen

1: /* 03L02.c: Calculate an addition and print out the result */

2: #include

3: /* This function adds two integers and returns the result */

4: int integer_add( int x, int y )

5: {

6: int result;

7: result = x + y;

8: return result;

9: }

10:

11: int main()

12: {

13: int sum;

14:

15: sum = integer_add(5, 12);

16: printf(“The addition of 5 and 12 is %d.\n”, sum);

17: return 0;

18: }

The program in Listing 3.2 is saved as a source file called 03L02.c. After this program is compiled and linked, an executable file for 03L02.c is created. On my machine, the executable file is named 03L02.exe. The following is the output printed on the screen after I run the executable on my machine:

The addition of 5 and 12 is 17.

OUTPUT

Line 1 in Listing 3.2 is a comment about the program. As you learned in Hour 2,
ANALYSIS
the include directive in line 2 includes the stdio.h header file because of the printf() function in the program.

Lines 3–9 represent the integer_add() function that adds two integers, as discussed in the previous section.

The main() function, prefixed with the int data type, starts in line 11. Lines 12 and 18

contain the opening brace and closing brace for the main() function, respectively. An integer variable, sum, is declared in line 13.

The statement in line 15 calls the integer_add() function that you examined in the previous section. Note that two integer constants, 5 and 12, are passed to the integer_add() function, and that the sum variable is assigned the return result from the integer_add() function.

05 067231861x CH03 4.10.2000 10:59 AM Page 51

Learning the Structure of a C Program

51

You first saw the C standard library function printf() in Hour 2. If you thought you found something new added to the function in line 16, you’re correct. This time, there are two arguments that are passed to the printf() function. They are the string “The addition of 5 and 12 is %d.\n” and the variable sum.

Note that a new symbol, %d, is added into the first argument. The second argument is the integer variable sum. Because the value of sum is going to be printed out on the screen, you might think that the %d has something to do with the integer variable sum. You’re right again. %d tells the computer the format in which sum should be printed on the screen.

More details on %d are covered in Hour 4. The relationship between %d and sum is discussed in Hour 5, “Handling Standard Input and Output.”

More importantly, you should focus on the program in Listing 3.2 and pay attention to how to call either a user-generated function or a standard C library function from the
3

main() function.

Summary

In this lesson you learned the following important concepts and operators:

• A constant in C is a value that never changes. A variable, on the other hand, can present different values.

• A combination of constants, variables, and operators is called an expression in the C language. An expression is used to denote different computations.

• The arithmetic operators include +, -, *, /, and %.

• A statement consists of a complete expression suffixed with a semicolon.

• The C compiler treats a statement block as a single statement, although the statement block might contain more than one statement.

• The function type specified in the declaration of a function determines the type of the value returned by the function.

• You have to follow certain rules to make a valid function name.

• An argument contains information that you want to pass to a function. An argument list contains two or more arguments that are separated by commas.

• The opening brace ({) and closing brace (}) are used to mark the start and end of a C function.

• A function body contains variable declarations and statements.

• Usually, a function should accomplish just one task.

In the next lesson you’ll learn more about data types in the C language.

05 067231861x CH03 4.10.2000 10:59 AM Page 52

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

Other books

Betsy and Billy by Carolyn Haywood
Green on Blue by Elliot Ackerman
The Teacher Wars by Dana Goldstein
The Dark Divide by Jennifer Fallon
MiNRS by Kevin Sylvester
Defiance by Behan, Tom
Last First Kiss by Vanessa Devereaux
Hot Spot by Debbi Rawlins


readsbookonline.com Copyright 2016 - 2024