SlideShare ist ein Scribd-Unternehmen logo
1 von 23
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.

Weitere ähnliche Inhalte

Was ist angesagt?

Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
myrajendra
 
Inline assembly language programs in c
Inline assembly language programs in cInline assembly language programs in c
Inline assembly language programs in c
Tech_MX
 

Was ist angesagt? (20)

INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Inline functions
Inline functionsInline functions
Inline functions
 
Command Line Arguments in C#
Command Line Arguments in C#Command Line Arguments in C#
Command Line Arguments in C#
 
inline function
inline function inline function
inline function
 
CPP07 - Scope
CPP07 - ScopeCPP07 - Scope
CPP07 - Scope
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macros
 
Java script function
Java script functionJava script function
Java script function
 
Basic c++
Basic c++Basic c++
Basic c++
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, Recursion
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
 
Inline and lambda function
Inline and lambda functionInline and lambda function
Inline and lambda function
 
Inline assembly language programs in c
Inline assembly language programs in cInline assembly language programs in c
Inline assembly language programs in c
 
Beyond Mere Actors
Beyond Mere ActorsBeyond Mere Actors
Beyond Mere Actors
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
C programming
C programmingC programming
C programming
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++
 

Ähnlich wie CPP06 - Functions

Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptx
sarthakgithub
 

Ähnlich wie CPP06 - Functions (20)

C++ Functions.pptx
C++ Functions.pptxC++ Functions.pptx
C++ Functions.pptx
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptx
 
5. Functions in C.pdf
5. Functions in C.pdf5. Functions in C.pdf
5. Functions in C.pdf
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Functions
FunctionsFunctions
Functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Functions
FunctionsFunctions
Functions
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
Functions
FunctionsFunctions
Functions
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 

Mehr von Michael Heron

Mehr von Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Kürzlich hochgeladen

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Kürzlich hochgeladen (20)

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 

CPP06 - Functions

  • 2. 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.
  • 3. 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.
  • 4. The Function #include <iostream> using namespace std; int main() { // Some Code } void this_is_a_function() { // Some More Code }
  • 5. 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.
  • 6. 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; }
  • 7. 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…
  • 8. 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’
  • 9. 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.
  • 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 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; }
  • 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> 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; }
  • 14. 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.
  • 15. 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.
  • 16. 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.
  • 17. 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.
  • 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; }
  • 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 • 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
  • 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 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.