C - Program - 2e - Chapter04.pdf
(
403 KB
)
Pobierz
Functions
4
Part I: The Basics
CHAPTER OBJECTIVES
Present the concept of a function—which is a modular block of
code—in the C++ language.
KEY TERMS AND CONCEPTS
arguments
automatic variable
C++ libraries
call-by-reference
call-by-value
called function
calling function
call statement
flags
function
function body
function call
function header line
function declaration or prototype
global variable
input arguments
local variable
return statement
return type
static variable
variable scope
Demonstrate the basic format for any C++ function.
Describe how to write functions and how to pass data
between them.
Introduce the notion of variable scope—how long a variable is
“alive” in a program.
Illustrate how the location of the variable declaration deter-
mines the scope of the variable.
Present many simple program examples to illustrate these basic
function concepts.
KEYWORDS AND OPERATORS
return
void
Little Picture, Big Picture
I
n the beginning chapters of this text, we saw functions used three different
ways. First, when we wrote our programs in Chapter 2 and 3, we used the
main
function to contain our program code. Next, we included various
libraries or the standard namespace so that we could use their functions, such
as the
srand()
and
rand()
when working with random numbers or
sqrt()
when
we needed the square root of a value. Last, we called functions that belonged
to classes—for example, when we added an element to a vector object, we
used the
push_back()
function.
In this chapter, we learn the basic mechanics of writing functions. Our
functions here will be standalone blocks of code that are designed to do a
specific task (or tasks). For example, the
srand()
and
rand()
functions within the
cstdlib library are standalone functions. In the “old days” of C programming, all
C-based software was constructed with these types of functions. But in the
programming world today, the world revolves around classes and objects. We
have used the string and vector classes by creating our own objects and calling
the class functions. We have also used the pre-defined objects in iostream (
cout
and
cin
). Don’t lose sight of our ultimate goal—to become experts at writing our
own classes—and classes contain functions that do the tasks defined in the
class “job description.”
Before we can begin writing our own classes, we need to write standalone
functions. It is not a difficult task, learning to write functions, but you must pay
attention to how the functions are set up. Then the jump from writing these
types of functions to class functions is small. Now is the time to concentrate on
the parts and the pieces, the prototypes and the calls, the input lists and the
return values. Spending time here will pay off when we get to classes, I promise.
4.1
Functions in C++
A
function
is a complete section of C++ code with a definite start point, an end
point, and its own set of variables. Functions can be passed data values and they
can return data. Whether the function is standalone or part of a class, it should be
designed so that it has one primary task to accomplish.
function
a discrete module or
unit of code that per-
forms specific tasks
179
180
Chapter 4
❚
Functions Part 1: The Basics
Life with Just a
main
Function
At this stage in your study of C++ programming, you are familiar with data vari-
ables and arithmetic operations, if and
switch
statements, as well as
for
,
do
while
, and
while
loops. We have also seen how to use the
cin
,
cout
and
getline
objects from iostream, and have used the string and vector classes. But
our entire program has been contained with the
main
function. Program 4-1
shows a simple program that asks the user her name and age, and writes the in-
formation to the screen.
Program 4-1
1 //How old are you?
2 //Entire program contained in the main function.
3 #include <iostream>
4 #include <string>
5
6 using namespace std;
7
8 int main()
9 {
10 int age;
11 string name;
12
13 //Write a greeting
14 cout << "\n Hello from a C++ program! \n";
15
16 //Ask for the user's name
17 cout << "\n What is your name? ";
18 getline(cin,name);
19
20 //Ask for age
21 cout << "\n How old are you? ";
22 cin >> age;
23
24 //Write information
25 cout << "\n Hi " << name << "! You are "
26
<< age << " years old. \n";
27
28 return 0;
29 }
Output
Hello from a C++ program!
What is your name? Mary Jones
How old are you? 39
Hi Mary Jones! You are 39 years old.
181
Section 4.1
❚
Functions in C++
Life with Functions
Nearly all of our C++ programs are more complicated than asking for a person’s
name and age. As a first look at how to write functions in C++, we’ll re-write this
program using functions. There are four separate tasks in Program 4-1, writing a
greeting, asking for the user’s name, age, followed by writing the information to the
screen. In Program 4-2 these four tasks have been broken out into four separate
blocks of code. These are functions. By breaking the different tasks into functions,
we organize the program into regions that accomplish specific tasks. For now, exam-
ine Program 4-2 and its output. We’ll dissect this program in the following section.
Program 4-2
1 //Simple Functions and How Old Are You?
2
3 #include <iostream>
4 #include <string>
5
6 using namespace std;
7
8 //Function prototypes (or declarations)
9 void WriteHello();
10 string AskForName();
11 int AskForAge();
12 void Write(string name, int age);
13
14 int main()
15 {
16 int age;
17 string name;
18
19 //Write a greeting
20 WriteHello();
//call, no inputs, no return value
21
22 //Ask for the user's name
23 name = AskForName();
//call, returns name
24
25 //Ask for age
26 age = AskForAge();
//call, value assign into age
27
28 //Write information
29 Write(name, age);
//call, pass name, age to Write
30
31 return 0;
32 }
33
34 //Function definitions follow main
35
36 //Write_Hello writes a greeting message to the screen
182
Chapter 4
❚
Functions Part 1: The Basics
37 void WriteHello()
38 {
39 cout << "\n Hello from a C++ function!\n";
40 }
41
42 //AskForAge asks the user for age, returns age.
43 int AskForAge()
44 {
45 int age;
46 cout << "\n How old are you? ";
47 cin >> age;
48 cin.ignore(); //remove enter key
49 return age;
50 }
51
52 //AskForName asks for the user's name
53 string AskForName()
54 {
55 string name;
56 cout << "\n What is your name? ";
57 getline(cin,name);
58 return name;
59 }
60
61
62 //Write writes the name and age to the screen
63 void Write(string name, int age)
64 {
65 cout << "\n Hi " << name << "! You are "
66
<< age << " years old. \n";
67 }
Output
Hello from a C++ function!
What is your name? Mary Jones
How old are you? 39
Hi Mary Jones! You are 39 years old.
Functions are Good
When writing a program, you should organize the code into logical building blocks.
This may involve laying out classes whose job tasks are then described and defined
with functions. (We’ll learn how to write classes in Chapter 7.) A well-written func-
tion can be reused in many programs. Use descriptive names for functions and
variables, write with an easy-to-read style, and trap for errors you might encounter.
You will then be well on your way to writing clearly understood software.
C programmers concentrated on writing functions. The function is the basic pro-
gramming unit in a C program. We are heading toward designing and writing classes
and using objects. In object-oriented software, the basic programming unit for C++ is
Plik z chomika:
Januszek66
Inne pliki z tego folderu:
Back Seat_ A Mumbai Tale - Aditya Kripalani.mobi
(755 KB)
Brief Wondrous Life of Oscar Wao, The - Junot Diaz.opf
(3 KB)
Don't Make Me Think, Revisited_ - Steve Krug.mobi
(9256 KB)
M. T. Anderson - Norumbegan 03 - The Empire of Gut and Bone # (v5.0).epub
(2209 KB)
M. T. Anderson - Norumbegan 02 - The Suburb Beyond the Stars # (v5.0).epub
(2105 KB)
Inne foldery tego chomika:
Dokumenty
Galeria
LUDLUM ROBERT
Midi - Kar
Mszał Rzymski PL
Zgłoś jeśli
naruszono regulamin