Introducing Functions
C++ comes with libraries of predefined functions
- Example: sqrt function returns, or computes, the square root of a number:
double the_root = sqrt(9.0);
- The number, 9.0, is called the argument
- the_root will contain 3.0
Function Calls
- sqrt(9.0) is a "function call."
- It invokes, or sets in action, the sqrt function
- The argument (9), can also be a variable or an expression
- A function call can be used like any expression:
double bonus = sqrt(sales) / 10;
cout << "The side of a square with area " << area
<< “ is “
<< sqrt(area);
What functions have we seen so far in this class?
- pow(base, exponent)
- sqrt(number)
- length()
- substr(index, numChars)
- getline(cin, stringVariable)
- setprecision(n)
- Any others?
What do they all have in common? Notice any similarities in their syntax?
Function Call Syntax
- Function_name (Argument_List)
- Argument_List is a comma separated list: (Argument_1, Argument_2, … , Argument_Last)
side = sqrt(area);
cout << "2.5 to the power 3.0 is "
<< pow(2.5, 3.0);
Libraries
- Predefined functions are found in libraries
- The library must be “included” in a program to make the functions available
- An include directive tells the compiler which library header file to include.
- To include the math library containing sqrt():
#include <cmath>
- Newer standard libraries, such as cmath, also require the directive
using namespace std;
Writing Our Own Functions
Grouping Repeated Commands
- Some of the
main() functions in our programs have been getting lengthy and complicated
- The biggest problem in developing software is managing the complexity of programs
- We can improve our code by organizing it into smaller pieces known as functions
- Functions are a key tool in creating easy-to-understand programs that can be changed easily
Video: Chris Bosh Explains Functions
-
After watching the video, what does it mean to write our own functions?
What is a Function?
Example Application for a Function
- As an example, recall our test code to validate user input:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#include <iostream>
using namespace std;
int main() {
double input = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(1000, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
cout << "You entered: " << input << endl;
return 0;
}
|
- What if we need to enter two validated numbers into a program?
- We want to process the first number after input and then input the second number
- Doing so, we would end up with code like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
#include <iostream>
using namespace std;
int main() {
double input = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(INT_MAX, '\n');
input = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
// Process the input
cout << "You entered: " << input << endl;
double input2 = 0.0;
do {
cout << "Enter a positive number: ";
cin >> input2;
if (cin.fail()) {
cout << "You must enter digits, not words\n";
cin.clear();
cin.ignore(INT_MAX, '\n');
input2 = -1; // set loop test to fail
} else if (input <= 0.0) {
cout << "You must enter a positive number\n";
}
} while (input <= 0.0);
// Process the second input
cout << "You entered: " << input2 << endl;
return 0;
}
|
- Our program would be easier to write if we could get the second input without repeating the code
- With functions, we give the list of commands a name and then run the list by calling the name
- Using functions we keep all the code in one place and avoid duplication
- Avoiding duplication reduces the complexity of our code and makes it easier to understand and change
Programming Style: Avoid Duplicating Code
- Duplicate code can lead to problems such as:
- Long repeated sections that are more difficult to understand than shorter sequences
- Repetition of largely identical code within which it is difficult to see the different purposes of each section
- Update problems where we make changes in some sections but overlook making changes in other sections
- If we find ourselves writing similar code of three or more lines multiple times, we should consider writing a function
Defining a Function
- In this section we look at function definition syntax and examine a simple example function
- After we understand the syntax we can write more complicated functions
Function Syntax
- The general syntax for defining a function is:
returnType functionName(parameter1, ..., parametern) {
statements
}
- Where:
- returnType: the data type of the value returned
- functionName: the name you make up for the function
- parameterx: the input values, if any
- statements: the list of statements to execute when the function is called
- Can you identify each of these syntax items in the function we have always used?
int main() {
// program statements go here
}
Example Program with a Second Function
- As an example, the following program has a simple function to add two numbers
- Notice that the code has two functions:
add() and main()
- The second function is placed before
main() so the compiler knows about the function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include <iostream>
using namespace std;
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << "Enter two numbers to add: ";
int num1, num2;
cin >> num1 >> num2;
int total = add(num1, num2);
cout << "Sum=" << total << endl;
return 0;
}
|
Function Name
- Every function must have a name that identifies the function
- Function names follow the same rules as variable names
- Technically, we can use any valid identifier for a function name
- However, we should use a name that suggests the action the function performs
- In our example, add suggests that the function will return the sum of two numbers
Function Structure
- The first line of a function is known as the function signature
int add(int a, int b)
- The curly braces
{...} contain the function body
- The function body is the list of statement the function executes when called
- The function signature describes the name, inputs and output of a function
- We will look at these features in more detail in the following sections
Parameters
- When defining a function, it is worth thinking about what helpful action it will perform
- We can make the function more useful if we give it parameters
- The parameters for an add function would be the two numbers to sum
- Read through the following code to identify how the code makes use of the parameters
Example Code with Function Parameters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include <iostream>
using namespace std;
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << "Enter two numbers to add: ";
int num1, num2;
cin >> num1 >> num2;
int total = add(num1, num2);
cout << "Sum=" << total << endl;
return 0;
}
|
Parameter List
- We must have parenthesis after a function name
- Inside the parenthesis, we define a list of zero or more parameters
- Parameters are the inputs to a function
- In our example, we have two parameters inside the parenthesis
int add(int a, int b)
- Parameters are the declaration of a new variable, even though they are declared inside parenthesis
- Each parameter must have both a type and a name, just like a regular variable
- If we have more than one parameter, we separate them with commas
- Any parameter that we declare must be given an argument when we call the function
- In the following image, the value of arguments
num1 and num2 are copied to the parameters a and b
Passing Arguments to Function Parameters
Arguments and Parameters
Returning a Value
- The first word in the function signature is the return type
int add(int a, int b)
- The return type specifies the type of data the function outputs
- In our example the return type is an
int
Return Statement
- Functions that return a value must execute a
return statement
return result;
- For instance, our example function
add() has a return statement
int add(int a, int b) {
int sum = a + b;
return sum;
}
- Note that the type of the returned valued must be compatible with the function return type
- The returned value is substituted for the function call in the calling code
sum =>[replaces]=> add(num1, num2)
- We must save the returned value if we want to process it later in the program
int total = add(num1, num2);
Returning a Value from a Function
Returning an Expression
- The value after the word
return can be an expression
- It does not have to be just the name of a variable
- We could rewrite our
return statement to the following:
return a + b;
Multiple return Statments
Activity 16.1: Writing a Function (10 pts)
In this exercise we define our own function.
Specifications
- Copy the following program into Eclipse, save it as
sub.cpp , and then compile and run the starter program to make sure you copied it correctly.
#include <iostream>
using namespace std;
// Define function here
int main() {
return 0;
}
- Write the signature for a function named
sub that receives two int numbers and returns an int value, like we did for the add() function
returnType sub(two_int_parameters)
- Add the curly braces for the function body:
{ } .
- Inside the function body, subtract the second parameter from the first and return the value, like we did for the
add() function.
int sum = a + b; // from add() function, CHANGE THIS!
return sum;
- Compile and run your code. What do you see when you compile? (click here)
- Inside the
main() function, enter these statements:
cout << "Enter two numbers to subtract: ";
int num1, num2;
cin >> num1 >> num2;
int diff = sub(num1, num2);
cout << "Difference=" << diff << endl;
The fourth line contains the function call.
- Compile and run your modified program and verify the output looks like:
Enter two numbers to subtract: 3 1
Difference=2
- Save your sub.cpp file and submit it to Canvas.
Completed Program
When finished, your application should look like the following.
|