Functions
Michael Heron
Introduction
• We’ve covered a lot of ground already with regards to C++.
• We have one more fundamental concept to discuss before we
move on to more advanced topics.
• We have already seen the power of making use of repetition
and selections to help us direct the flow of execution through
a program.
• Today we are going to talk about the way in which we can
‘chunk’ these together into cohesive units called functions.
• Or methods.
Functions
• Functions are independent stubs of code that sit idle and
indolent until summoned into action by the developer.
• Except for the main function, which is special.
• Functions allow us to separate out logically cohesive
collections of statements.
• We can then use this function as a shorthand for the functionality
itself.
• It’s easier to see this in practice than it is to describe.
The Function
#include <iostream>
using namespace std;
int main() {
// Some Code
}
void this_is_a_function() {
// Some More Code
}
Important Points
• A function does not belong to main.
• It sits outside of main.
• A function must have braces.
• You can’t get away with not using them like you can with an if or a
for.
• Although you shouldn’t be doing that either…
• Functions have a return type.
• In this case, it’s void.
• Functions have none or more parameters.
• This function has no parameters.
Example Program
#include <iostream>
using namespace std;
void print_to_screen() {
cout << "Please enter a number:" << endl;
}
int main() {
int num1, num2;
print_to_screen();
cin >> num1;
print_to_screen();
cin >> num2;
cout << "The sum is " << (num1 + num2) << endl;
}
Functions
• Whenever we use the line of code print_to_screen(), the
compiler will make use of the function we have provided.
• In technical terms, the function is:
• Called, or
• Executed, or
• Invoked
• We can thus break out functionality into more easily managed
chunks.
• One very large program is hard to ‘grok’
• You will get Geek Chic Points if you use that term in conversation.
• Small functions are easier to comprehend.
• Although they can make it harder to see the big picture.
• That’s not our problem in this module though…
Functions
• Functions can be as complex as we need them to be.
• There are some general guidelines for writing a good function:
• As small as is possible.
• Around a single page on your IDE is about right
• As precise a role as is possible
• A function should do one thing and one thing only.
• Large and impossible tasks are rendered achievable through
the use of functional decomposition.
• This is a fancy way of saying ‘break the whole down into the sum
of its parts’
Functional Decomposition
• This is a tremendously important technique.
• The hardest thing in programming is not the syntax of the
code.
• That eventually becomes second nature.
• Actually being able to apply that code is the tricky bit.
• Often you are given tasks that you have no real way of being able
to solve as a whole.
• You solve them by implementing the code incrementally.
• We see this in the tutorial exercises.
Functions Again
• C++ requires us to adhere to a particular layout of functions.
• Before we can use a function in code, C++ must be aware of the
function.
• This is either done by:
• putting the function code before where it is used.
• Not a great solution, because code gets changed about all the time.
• putting a prototype of that function at the top of the file.
• This has its own drawbacks.
++ OUT OF CHEESE ERROR++
#include <iostream>
using namespace std;
int main() {
int num1, num2;
print_to_screen();
cin >> num1;
print_to_screen();
cin >> num2;
cout << "The sum is " << (num1 + num2) << endl;
}
void print_to_screen() {
cout << "Please enter a number:" << endl;
}
Function Prototypes
• C++ needs to know what the structure of a function is before
it uses it.
• It needs to know:
• The function name
• The function return type
• The type and order of parameters
• It doesn’t need to know the code.
• It will assume the code is provided somewhere.
This Works…
#include <iostream>
using namespace std;
// This is the function prototype.
void print_to_screen();
int main() {
int num1, num2;
print_to_screen();
cin >> num1;
print_to_screen();
cin >> num2;
cout << "The sum is " << (num1 + num2) << endl;
}
void print_to_screen() {
cout << "Please enter a number:" << endl;
}
Parameters
• Parameters are pieces of information we provide to a
function.
• The information it needs in order to do its job.
• For example, if we had a function that added two numbers
together…
• … we’d need to be able to provide it with two numbers
• We do this through parameters.
Parameters
• We can provide as many parameters as we like.
• Each comes as a pair, consisting of:
• A type
• And a name
• Within the function, they act like variables.
• You can manipulate them and access them in whatever way you feel
is necessary.
• When we provide information to a function, we refer to this as
parameter passing.
• We pass the parameter to the function.
Parameters
• When we invoke a function that has parameters, we need to provide
that information in the function call.
• We can do this as literal values:
• add_two_numbers (10, 20);
• Or from variables:
• add_two_numbers (num1, num2);
• The order in which we pass the variables will determine which
variable gets which name in the parameter list.
Return Type
• We often want to get information out of a function.
• We do this by returning a value to the invoker code.
• For this we use the special keyword return
• This means ‘stop executing the function, and give the following
information back to the function that invoked us’
• The return type of a function determines what kind of information
comes back out.
• If no information comes out, we use the special keyword void.
A Full Function
#include <iostream>
using namespace std;
int subtract (int, int);
int main() {
int num1, num2;
int answer;
cout << "What is the first number?";
cin >> num1;
cout << "What is the second number?";
cin >> num2;
answer = subtract (num1, num2);
cout << "The answer is " << answer << endl;
}
int subtract (int num1, int num2) {
return num1 - num2;
}
Functions and Parameters
Predefined Functions
• C++ comes stocked with a large number of predefined
functions.
• To get access to these, we need to #include the right header
file.
• This gives the necessary information to C++ to make use of the
function.
• Some of them can be used right away without including
another other than what we already have.
Predefined Functions
• You can get access to some of these by including the math.h header:
• Ceil, which rounds up:
• float rounded_val = ceil (6.6);
• Returns 7
• Floor, which rounds down:
• float rounded_val = ceil (6.6);
• Returns 6
• Pow, which gives the power of one number to another:
• float num = pow (2, 3);
• Returns 8
• Abs, which gives the absolute value of a number
• int num = abs (-5);
• Returns 5
Predefined Functions
#include <iostream>
#include <math.h>
using namespace std;
int subtract (int, int);
int main() {
int num1, num2;
int answer;
cout << "What is the first number?";
cin >> num1;
cout << "What is the second number?";
cin >> num2;
answer = pow (num1, num2);
cout << "The answer is " << answer << endl;
}
Summary
• Functions allow us to adopt a ‘divide and conquer’ approach
to our code.
• Break it up into easily managed chunks.
• Functions must be prototyped in some way.
• Functions can have parameters.
• Functions have a return type.
• We can make use of predefined functions that are part of the
standard C++ library.

CPP06 - Functions

  • 1.
  • 2.
    Introduction • We’ve covereda lot of ground already with regards to C++. • We have one more fundamental concept to discuss before we move on to more advanced topics. • We have already seen the power of making use of repetition and selections to help us direct the flow of execution through a program. • Today we are going to talk about the way in which we can ‘chunk’ these together into cohesive units called functions. • Or methods.
  • 3.
    Functions • Functions areindependent stubs of code that sit idle and indolent until summoned into action by the developer. • Except for the main function, which is special. • Functions allow us to separate out logically cohesive collections of statements. • We can then use this function as a shorthand for the functionality itself. • It’s easier to see this in practice than it is to describe.
  • 4.
    The Function #include <iostream> usingnamespace std; int main() { // Some Code } void this_is_a_function() { // Some More Code }
  • 5.
    Important Points • Afunction does not belong to main. • It sits outside of main. • A function must have braces. • You can’t get away with not using them like you can with an if or a for. • Although you shouldn’t be doing that either… • Functions have a return type. • In this case, it’s void. • Functions have none or more parameters. • This function has no parameters.
  • 6.
    Example Program #include <iostream> usingnamespace std; void print_to_screen() { cout << "Please enter a number:" << endl; } int main() { int num1, num2; print_to_screen(); cin >> num1; print_to_screen(); cin >> num2; cout << "The sum is " << (num1 + num2) << endl; }
  • 7.
    Functions • Whenever weuse the line of code print_to_screen(), the compiler will make use of the function we have provided. • In technical terms, the function is: • Called, or • Executed, or • Invoked • We can thus break out functionality into more easily managed chunks. • One very large program is hard to ‘grok’ • You will get Geek Chic Points if you use that term in conversation. • Small functions are easier to comprehend. • Although they can make it harder to see the big picture. • That’s not our problem in this module though…
  • 8.
    Functions • Functions canbe as complex as we need them to be. • There are some general guidelines for writing a good function: • As small as is possible. • Around a single page on your IDE is about right • As precise a role as is possible • A function should do one thing and one thing only. • Large and impossible tasks are rendered achievable through the use of functional decomposition. • This is a fancy way of saying ‘break the whole down into the sum of its parts’
  • 9.
    Functional Decomposition • Thisis a tremendously important technique. • The hardest thing in programming is not the syntax of the code. • That eventually becomes second nature. • Actually being able to apply that code is the tricky bit. • Often you are given tasks that you have no real way of being able to solve as a whole. • You solve them by implementing the code incrementally. • We see this in the tutorial exercises.
  • 10.
    Functions Again • C++requires us to adhere to a particular layout of functions. • Before we can use a function in code, C++ must be aware of the function. • This is either done by: • putting the function code before where it is used. • Not a great solution, because code gets changed about all the time. • putting a prototype of that function at the top of the file. • This has its own drawbacks.
  • 11.
    ++ OUT OFCHEESE ERROR++ #include <iostream> using namespace std; int main() { int num1, num2; print_to_screen(); cin >> num1; print_to_screen(); cin >> num2; cout << "The sum is " << (num1 + num2) << endl; } void print_to_screen() { cout << "Please enter a number:" << endl; }
  • 12.
    Function Prototypes • C++needs to know what the structure of a function is before it uses it. • It needs to know: • The function name • The function return type • The type and order of parameters • It doesn’t need to know the code. • It will assume the code is provided somewhere.
  • 13.
    This Works… #include <iostream> usingnamespace std; // This is the function prototype. void print_to_screen(); int main() { int num1, num2; print_to_screen(); cin >> num1; print_to_screen(); cin >> num2; cout << "The sum is " << (num1 + num2) << endl; } void print_to_screen() { cout << "Please enter a number:" << endl; }
  • 14.
    Parameters • Parameters arepieces of information we provide to a function. • The information it needs in order to do its job. • For example, if we had a function that added two numbers together… • … we’d need to be able to provide it with two numbers • We do this through parameters.
  • 15.
    Parameters • We canprovide as many parameters as we like. • Each comes as a pair, consisting of: • A type • And a name • Within the function, they act like variables. • You can manipulate them and access them in whatever way you feel is necessary. • When we provide information to a function, we refer to this as parameter passing. • We pass the parameter to the function.
  • 16.
    Parameters • When weinvoke a function that has parameters, we need to provide that information in the function call. • We can do this as literal values: • add_two_numbers (10, 20); • Or from variables: • add_two_numbers (num1, num2); • The order in which we pass the variables will determine which variable gets which name in the parameter list.
  • 17.
    Return Type • Weoften want to get information out of a function. • We do this by returning a value to the invoker code. • For this we use the special keyword return • This means ‘stop executing the function, and give the following information back to the function that invoked us’ • The return type of a function determines what kind of information comes back out. • If no information comes out, we use the special keyword void.
  • 18.
    A Full Function #include<iostream> using namespace std; int subtract (int, int); int main() { int num1, num2; int answer; cout << "What is the first number?"; cin >> num1; cout << "What is the second number?"; cin >> num2; answer = subtract (num1, num2); cout << "The answer is " << answer << endl; } int subtract (int num1, int num2) { return num1 - num2; }
  • 19.
  • 20.
    Predefined Functions • C++comes stocked with a large number of predefined functions. • To get access to these, we need to #include the right header file. • This gives the necessary information to C++ to make use of the function. • Some of them can be used right away without including another other than what we already have.
  • 21.
    Predefined Functions • Youcan get access to some of these by including the math.h header: • Ceil, which rounds up: • float rounded_val = ceil (6.6); • Returns 7 • Floor, which rounds down: • float rounded_val = ceil (6.6); • Returns 6 • Pow, which gives the power of one number to another: • float num = pow (2, 3); • Returns 8 • Abs, which gives the absolute value of a number • int num = abs (-5); • Returns 5
  • 22.
    Predefined Functions #include <iostream> #include<math.h> using namespace std; int subtract (int, int); int main() { int num1, num2; int answer; cout << "What is the first number?"; cin >> num1; cout << "What is the second number?"; cin >> num2; answer = pow (num1, num2); cout << "The answer is " << answer << endl; }
  • 23.
    Summary • Functions allowus to adopt a ‘divide and conquer’ approach to our code. • Break it up into easily managed chunks. • Functions must be prototyped in some way. • Functions can have parameters. • Functions have a return type. • We can make use of predefined functions that are part of the standard C++ library.