C++ Functions
C++ Functions
Agenda
Scope of variables
The Top-down design appeoach is based on dividing the main problem into smaller tasks which may be divided into simpler tasks, then implementing each simple task by a subprogram or a function A C++ function or a subprogram is simply a chunk of C++ code that has
computeTaxes to compute the taxes for an employee isPrime to check whether or not a number is a prime number
A returning value
The computeTaxes function may return with a double number representing the amount of taxes The isPrime function may return with a Boolean value (true or false)
C++ language is shipped with a lot of functions which are known as standard functions These standard functions are groups in different libraries which can be included in the C++ program, e.g.
Math functions are declared in <math.h> library Character-manipulation functions are declared in <ctype.h> library C++ is shipped with more than 100 standard libraries, some of them are very popular such as <iostream.h> and <stdlib.h>, others are very specific to certain hardware platform, e.g. <limits.h> and <largeInt.h>
Although C++ is shipped with a lot of standard functions, these functions are not enough for all users, therefore, C++ provides its users with a way to define their own functions (or userdefined function) For example, the <math.h> library does not include a standard function that allows users to round a real number to the ith digits, therefore, we must declare and implement this function ourselves
7
Generally speaking, we define a C++ function in two steps (preferably but not mandatory)
Step #1 declare the function signature in either a header file (.h file) or before the main function of the program Step #2 Implement the function in either an implementation file (.cpp) or after the main function
The function header has the following syntax <return value> <name> (<parameter list>) The function body is simply a C++ code enclosed between { }
double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; }
10
double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; }
11
Function body
double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; }
12
Function Signature
The function signature is actually similar to the function header except in two aspects:
The parameters names may not be specified in the function signature The function signature must be ended by a semicolon
Example
Unnamed Parameter
Semicolon ;
double computeTaxes(double) ;
13
If you want to create your own library and share it with your customers without letting them know the implementation details, you should declare all the function signatures in a header (.h) file and distribute the binary code of the implementation file
By only sharing the function signatures, we have the liberty to change the implementation details from time to time to
Improve function performance make the customers focus on the purpose of the function, not its implementation
14
Example
#include <iostream> #include <string> using namespace std; // Function Signature double getIncome(string); double computeTaxes(double); void printTaxes(double); void main() { // Get the income; double income = getIncome("Please enter the employee income: "); // Compute Taxes double taxes = computeTaxes(income); // Print employee taxes printTaxes(taxes); } double computeTaxes(double income) { if (income<5000) return 0.0; return 0.07*(income-5000.0); } double getIncome(string prompt) { cout << prompt; double income; cin >> income; return income; } void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl; }
15
How to create header files to store function signatures How to create implementation files to store function implementations How to include the header file to your program to use your user-defined functions
16
The C++ header files must have .h extension and should have the following structure
#ifndef compiler directive #define compiler directive May include some other header files All functions signatures with some comments about their purposes, their inputs, and outputs #endif compiler directive
17
double getIncome(string); // purpose -- to get the employee income // input -- a string prompt to be displayed to the user // output -- a double value representing the income
18
Inline Functions
Inline functions are very small functions, generally, one or two lines of code Inline functions are very fast functions compared to the functions declared without the inline keyword
Example #1
Write a function to test if a number is an odd number inline bool odd (int x) { return (x % 2 == 1); }
22
Example #2
Write a function to compute the distance between two points (x1, y1) and (x2, y2) Inline double distance (double x1, double y1, double x2, double y2) { return sqrt(pow(x1-x2,2)+pow(y1-y2,2)); }
23
Example #3
Write a function to compute n! int factorial( int n) { int product=1; for (int i=1; i<=n; i++) product *= i; return product; }
24
Write functions to return with the maximum number of two numbers inline int max( int x, int y) { if (x>y) return x; else return y; } inline double max( double x, double y) { if (x>y) return x; else return y; }
25 An overloaded function is a function that is defined more than once with different data types or different number of parameters
global variables (very bad practice!) Passing data through function parameters
Value
26
C++ Variables
A name or identifier (e.g. income, taxes, etc.) A data type (e.g. int, double, char, etc.) A size (number of bytes) A scope (the part of the program code that can use it)
Global variables all functions can see it and using it Local variables only the function that declare local variables see and use these variables
Global variables can live as long as the program is executed Local variables are lived only when the functions that define these variables are executed
27
void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl ; }
void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl ; }
void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl; }
void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl; }
Not safe!
If two or more programmers are working together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value!
Exposing the global variables to all functions is against the principle of information hiding since this gives all functions the freedom to change the values stored in the global variables at any time (unsafe!)
44
Local Variables
Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit You have to initialize the local variable before using it If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable
45
void fun() { int x = 10; // Local variable cout << x << endl; }
46
void fun() { int x = 10; // Local variable cout << x << endl; }
47
void fun() { int x = 10; // Local variable cout << x << endl; }
48
void fun()
x
{ 3 }
void fun() { int x = 10; // Local variable cout << x << endl; }
49
void fun()
x
{ 3 }
void fun() { int x = 10; // Local variable cout << x << endl; }
50
void fun()
x
{ 4 }
void fun()
x
{
55
Value Parameters
This is what we use to declare in the function signature or function header, e.g.
Here, parameters x and y are value parameters When you call the max function as max(4, 7), the values 4 and 7 are copied to x and y respectively When you call the max function as max (a, b), where a=40 and b=10, the values 40 and 10 are copied to x and y respectively When you call the max function as max( a+b, b/2), the values 50 and 5 are copies to x and y respectively
Once the value parameters accepted copies of the corresponding arguments data, they act as local variables!
56
Reference Parameters
As we saw in the last example, any changes in the value parameters dont affect the original function arguments Sometimes, we want to change the values of the original function arguments or return with more than one value from the function, in this case we use reference parameters
A reference parameter is just another name to the original argument variable We define a reference parameter by adding the & in front of the parameter name, e.g.
void fun( int & y { cout<<y<<endl; y=y+5; } void main() { ? 4 int x = 4; fun(x); cout << x << endl; }
void fun( int & y { cout<<y<<endl; y=y+5; 9 } void main() { ? 4 int x = 4; fun(x); cout << x << endl; }
void fun( int & y { cout<<y<<endl; y=y+5; } void main() { ? 9 int x = 4; fun(x); cout << x << endl; }
Constant reference parameters are used under the following two conditions:
The passed data are so big and you want to save time and computer memory The passed data will not be changed or updated in the function body
For example void report (const string & prompt); The only valid arguments accepted by reference parameters and constant reference parameters are variable names
70
It is a syntax error to pass constant values or expressions to the (const) reference parameters