Download presentation
Presentation is loading. Please wait.
1
Introduction to C++ computers and programming
CMPT 129 © Janice Regan, CMPT
2
Modulariz1ation When solving a real engineering (or other) programming problem it will be necessary to break the problem into pieces or modules. Each module can be separately developed and debugged Modules can then be assembled and tested to build the solution to the entire problem When programming in C++ it is often useful to write each module as one or more functions (process oriented) or methods (object oriented). A function is an independent program that solves a problem. That problem is often a component of a larger problem. © Janice Regan, CMPT
3
Modularization Any module, method, or function can use (call) any other function When designing a process oriented solution for a larger problem it is often useful to draw a map of which functions call which other functions (structure chart or module chart) A function can even call itself. Such a function is called a recursive function and requires special care to design Beware of unintended recursion (most commonly function1 calling function2 which calls function1, this type of recursion is also called indirect recursion). This can cause serious problems. © Janice Regan, CMPT
4
Module Chart fun5 fun2 fun9 fun8 fun4 fun7 fun6 fun3 fun1 main
recursion Indirect recursion © Janice Regan, CMPT
5
Types of functions: predefined
Functions can be predefined functions Functions provided by the C++ language (or other programming language) to accomplish common tasks Trigonometric and mathematical functions Input and output functions System functions (networking etc.) Random number generators Other tools © Janice Regan, CMPT
6
Types of functions: user defined
Functions can be "user defined" functions Written by the developer for applications specific to the developers needs Part of libraries associated with particular tools (outside the C++ compiler) being used by the developer to build more complex applications Graphics libraries Statistical analysis libraries © Janice Regan, CMPT
7
Refer to the function that is being asked for as the called function.
Calling function A function can be called from your main function (or from any other function). Refer to the function (e.g. main) that asks to use another function as the calling function Refer to the function that is being asked for as the called function. © Janice Regan, CMPT
8
Function Declaration/prototype
3 steps: functions Function Declaration/prototype Information than the compiler needs to properly interpret calls to the function Function Definition Actual implementation of the function Function Call Using the function in the calling function © Janice Regan, CMPT
9
Function Declaration/prototype
3 steps: functions Function Declaration/prototype Information than the compiler needs to properly interpret calls to the function Function Definition Actual implementation of the function Function Call Using the function in the calling function © Janice Regan, CMPT
10
Function prototypes When you use a C++ function you should declare the function at the beginning of the file containing your program. The declaration of a function is called a function prototype #include <iostream> using namespace std; double myFunction( int myData ); int myFunction2( double A, int B, int c); int main( ) { …. © Janice Regan, CMPT
11
Prototype A function prototype is a statement describing the function that you wish to call in your program A function prototype is used by the compiler to match the function called in the program to a function that is user defined or a predefined function from a library A function prototype does not include the code implementing the body of the called function © Janice Regan, CMPT
12
When to write function prototypes
Every function called in a program needs to have a prototype However, sometimes you do not have to write the function’s prototype yourself If the function is part of a library then you will have a statement in your program like #include <library/object> For functions in such libraries/objects the prototypes will be provided for you. HOW??? © Janice Regan, CMPT
13
Provided function prototypes
If the function is part of a library or an object you will have a statement in your program like #include <library or object> The C++ preprocessor replaces this preprocessor statement with a list of the prototypes, one for each of the functions in the library or methods in the object Then the compiler compiles your code Therefore, before your code compiles it includes prototypes of all functions in the library © Janice Regan, CMPT
14
Declaring a user’s function
A function prototype tells us (and the compiler) the type of the function The identifier of the function The type of each parameter The identifier of each parameter (optional) The order of the parameters The function prototype is usually placed after the #include statements before the int main () statement The function can then be called by any other functions © Janice Regan, CMPT
15
Return type and function identifier
The return type indicates the type of the value returned by the function When the function is called the statement calling the function can be considered to be an expression The value of this expression (the call) in the calling function has a type, return type The function identifier (function name) indicates the name of the function © Janice Regan, CMPT
16
Parameter list <return type> <function identifier> (<parameter list >); int myMean ( int a, int b, int c, int d); double sumSquares(double in1,double in2); bool isReady ( int , double , int ); In a prototype parameter identifiers for all parameters in the parameter list are optional In a prototype parameter type for all parameters in the parameter list are required © Janice Regan, CMPT
17
What are parameters A series of parameters (or arguments) follow the function identifier. These parameters represent the variable values supplied to (and sometimes under special conditions returned from) the function Each parameter is of a particular data type that is specified within the declaration The order of the parameters is important. The order must be the same in the prototype, the definition of the function and the call to the function. © Janice Regan, CMPT
18
MORE about parameters The function can have any number of parameters.
Each parameter of the function can have any type Different parameters of the same function can have different types Order of the parameters is important Parameters in the declaration, definition, and call must always be in the same order © Janice Regan, CMPT
19
Prototypes: an example
As an example consider double sinc ( double x ); OR double sinc ( double ); The identifier (name) of the function is sinc The function returns a value of type double to the calling function the expression sinc(inputvalue) in the calling function, is of type double and has the value returned by the return statement/s in function sinc The parameter list contains a single parameter of type double An identfier for the parameter may be given (optional) © Janice Regan, CMPT
20
Predefined functions No need to write your own function prototypes
Prototypes are supplied by #Include of the library Prototypes are added by the preprocessor No need to write your own definition of the function The definition of the function (the code to implement the function) exists in the library Predefined functions are used in the same way as user defined functions © Janice Regan, CMPT
21
Function Declaration/prototype
3 steps: functions Function Declaration/prototype Information than the compiler needs to properly interpret calls to the function Function Definition Actual implementation of the function Function Call Using the function in the calling function © Janice Regan, CMPT
22
Function Definition Two main parts Function Head Function Body
Gives the compiler information to match the function with the function declaration Function Body Actual C++ statements implementing the function Function definitions are placed after or before the main function (not inside the main function) For out class coding standard functions are placed after the main program, prototypes before the main © Janice Regan, CMPT
23
Placement of Function Definition
int main () { // body of main function } double sinc(double x) // function head //function body © Janice Regan, CMPT
24
Sample Function Definition
double sinc(double x) { if (fabs(x) < ) return(1.0); } else return( sin(x)/x); Function head Function body Function call to library function sin © Janice Regan, CMPT
25
Function Head (examples)
The first line of a function definition is the function head The head for the main function is int main ( ) The head for our example function is double sinc (double x) There is no ; at the end of a function head © Janice Regan, CMPT
26
Function Head (content)
The function head indicates the type of the function double sinc( double x ) The function head indicates a function name or identifier The function head indicates a list of parameters for the function, each parameter includes a type and an identifier double sinc (double x) © Janice Regan, CMPT
27
Function head: formal parameters
The parameters in the function head are referred to as formal parameters The function has 0 or more formal parameters double sinc( double x ) Each of a function’s formal parameters have types A function may have formal parameters of more than one type Each parameter must be given its own type Multiple parameters are separated by commas int sample( double x, int y, char z, double a) © Janice Regan, CMPT
28
The body of a function After the function head the body of the function is enclosed in {} double sinc(double x) { //variable declarations double y; //declaring variable //for return value //calculations to determine y return y; } Function body © Janice Regan, CMPT
29
Parts of the function body
Local variables are declared Calculate the return value of the function Return the value to the calling function return returnValue; In a more complicated function you must assure all possible paths to completion of a function end with a return statement For a void function return statements are not required Return statements without arguments may be used to return from the function to the calling program © Janice Regan, CMPT
30
Sample Function Definition
double sinc(double x) { if (fabs(x) < ) return(1.0); } else return( sin(x)/x); Function head Function body Return statements © Janice Regan, CMPT
31
Function Declaration/prototype
3 steps: functions Function Declaration/prototype Information than the compiler needs to properly interpret calls to the function Function Definition Actual implementation of the function Function Call Using the function in the calling function © Janice Regan, CMPT
32
Using our sample function
// declare functions used double sinc(double x); int main (void) { // declare variables double a, b; // obtain input data a, call function, print results cout << “ enter value for which sinc is to be determined “); cin >> a; b= sinc(a); cout << "sinc( " << a << " ) = " << b; } Function prototype or function declaration Function call © Janice Regan, CMPT
33
Calling a function double abs(double x); //prototype
limitValue = abs(-9.7); // call abs(-9.7) is an expression known as a function call, or function invocation The arguments in the brackets ( ) of a function call are called actual arguments or actual parameters. An actual argument in a function call can be A literal (like -9.7) any variable whose value is of the correct type any expression whose value is of the correct type © Janice Regan, CMPT
34
Predefined function sqrt()
double sqrt(double x); // prototype theRoot = sqrt(25.0); // use sqrt identifier (name) of library function value of formal argument x is actual argument 25.0 C or C++ expression sqrt(x) has the value 𝑥 The value of the expression sqrt(25.0) is 5.0 5.0 is placed in the double variable theRoot © Janice Regan, CMPT
35
Reusing functions double sin(double x); // prototype
double quantity=2.5; double bone=3.6; sinValue1 = sin( quantity ); // use sinValue2 = sin( bone ); Within a single program you can call the function any number of times using any number of different actual arguments (like quantity or bone) Within a single program you can call the function any number of times using the same actual argument (same variable). The value of the variable that is the actual argument may change from call to call © Janice Regan, CMPT
36
functions >1 argument
double pow(double base, int power); double quantity = 25.5; int bone = 12; powValue = pow( quantity, bone ); You must have the same number of arguments in your call to the function as there are arguments in the prototype for the function (except when default arguments are used) Arguments in your call to the function must be in the same order as the arguments in the declaration of the function. Each argument in your call to the function must have the same type as the corresponding argument in the declaration © Janice Regan, CMPT
37
Functions: Specifying default parameters
You may give the formal parameters of a user defined function default values. If you have a prototype before the definition of a function the prototype becomes double myFunc ( int = 23, double =33.5 ); OR double myFunct( int appNum=23, double appDay = 33.5); Otherwise the head of the definition becomes double myFunct( int appNum=23, double appDay = 33.5) © Janice Regan, CMPT
38
Functions: using default parameters
When writing a prototype (or header) that includes defaulted parameters after a parameter with a default argument, all subsequent parameters must have a default arguments When calling a function with defaulted parameters the default is used if there is no actual parameter that corresponds to the defaulted formal parameter After a defaulted formal parameter is omitted in a function call, all remaining formal parameters must be omitted (must take the default values) © Janice Regan, CMPT
39
Functions: types bool isless (double x, double y); // returns true if x<y double x = 23.4; double y = 44.1; if ( boolValue = isless( a1, b1)) { cout << “a1 < b1” ; } Functions can return values of different types. This function returns a boolean value. The previous examples returned double values Functions can be used as parts of more complicated expressions © Janice Regan, CMPT
40
Returning a function’s value
The function has a type. The type of the function is the type of the value returned by that function to the calling program A non-void function will take the supplied values of the actual parameters, calculate a result, then return that result to the calling program A void function does not return a value When a non void function is invoked using a function call, the function call expression is given the value that is returned by the function © Janice Regan, CMPT
41
Returning a function’s value (2)
Our sample function determines the value of sin(x)/x when we supply a value for the parameter x The function sinc(x) will take the value of x, calculate the value of sin(x)/x and return the resulting value to the calling program To return the value of the function to the calling program following command is used return(ValueToBeReturned); The type of variable or expression ValueToBeReturned should match the type of the function returning the value A function of any type other than void must contain at least one return statement. It may contain more. There must be 1 return statement ending each flow of control through the function © Janice Regan, CMPT
42
Calling Void Functions
For a function declared as void showResults(double x, double y); Can call the function in a calling function as follows showResults(degreesF, degreesC); showResults(32.5, 0.3); A function call to a void function does not have a value, because a void function does not return a value. A = showResults(32.5,0.3) * 3.0; //this is an invalid statement A function call to a void function has no value to be used in an arithmetic expression ( or any other kind of expression) A function call to a void function cannot be assigned to a variable since it has no value to place in that variable © Janice Regan, CMPT
43
Using a function Once we have declared and defined a function we can then use it in the body of our function or main program The value of the functional calling expression has the same type as the function and will contain the value returned by the function. The identifier for a variable that is used in place of a parameter must identify a variable with the same type as that parameter. © Janice Regan, CMPT
44
What happens: calling a function
int fun1( int value1, int value2); Main program calls function myb =fun1(a, b); Variables used in main int myb = 0; int a = 5; int b = 10; myb = fun1(a, b); Computer memory © Janice Regan, CMPT
45
What happens: calling a function
int fun1( int value1, int value2); Main program calls function myb =fun1(a, b); Computer makes a new ‘frame’ for executing function fun1 Variables used in main int , myb = 0; int a = 5; int b = 10; myb = fun1(a, b); Computer memory © Janice Regan, CMPT
46
What happens: calling a function
Main program calls function Value=fun1(value1, value2); Computer makes a new ‘frame’ for executing function fun1 The values of a and b are copied to the new frame and placed in formal arguments value1 and value2 respectively Variables used in main int , myb = 0; int a = 5; int b = 10; myb = fun1(a, b); Variables used in fun1 int result = 0; value2 =10; value1 = 5; Computer memory © Janice Regan, CMPT
47
What happens: calling a function
Main program calls function Value=fun1(value1, value2); Computer makes a new ‘frame’ for executing function fun1 The values of a and b are copied to the new frame and placed in formal arguments value1 and value2 respectively The return value of the function, myb is calculated using value1 and value2 Variables used in main int , myb = 0; int a = 5; int b = 10; myb = fun1(a, b); Variables used in fun1 int result = 0; value2 = b; value1 = a; Result = ? Computer memory © Janice Regan, CMPT
48
What happens: calling a function
Main program calls function Value=fun1(value1, value2); Computer makes a new ‘frame’ for executing function fun1 The values of a and b are copied to the new frame and placed in formal arguments value1 and value2 respectively The return value of the function, myb is calculated using value1 and value2 The return value of the function is sent back to main Variables used in main int , myb = 0; int a = 5; int b = 10; myb = fun1(a, b); Variables used in fun1 int result = 0; value2 = b; value1 = a; Result = ? Computer memory © Janice Regan, CMPT
49
What happens: calling a function
Main program calls function Value=fun1(value1, value2); Computer makes a new ‘frame’ for executing function fun1 The values of a and b are copied to the new frame and placed in formal arguments value1 and value2 respectively The return value of the function, myb is calculated using value1 and value2 The return value of the function is sent back to main The new ‘frame’ for fun1 is destroyed Any changes to the values of variables in the new ‘frame’ are lost Variables used in main int , myb = 0; int a = 5; int b = 10; myb = ? Computer memory © Janice Regan, CMPT
50
Consequences of what happens
The value of an actual parameter cannot be changed inside a function When the new frame is made the values of the actual parameters are copied into the formal parameters If the value of the formal parameter is changed in the function, only the value in the new ‘frame’ is changed. When the new function ‘frame’ is destroyed, The only information remaining is the value returned to the calling function The function cannot access the actual parameter, the value of the actual parameter is not changed © Janice Regan, CMPT
51
Swap function Consider an incorrect function trying to swap two values
void swap( int value1, int value2) { double tmp; tmp = value1; value1 = value2; value2 = tmp; //The values in variables value1 and value 2 //have been exchanged } © Janice Regan, CMPT
52
What happens: calling a function
void swap( int a, int b) Main program calls function swap(Value1, Value2); Computer makes a new ‘frame’ for executing function swap Variables used in main int value1 = 10; int value 2 = 15; swap( value1, value2) Computer memory © Janice Regan, CMPT
53
What happens: calling a function
void swap( int a, int b) Main program calls function swap(Value1, Value2); Computer makes a new ‘frame’ for executing function swap The values of the actual parameters Value1 and Value2 are copied into the formal parameters in the new frame for the function Variables used in main int value1 = 10; int value 2 = 15; swap( value1, value2) Variables passed into swap a = 10; b = 15; Computer memory © Janice Regan, CMPT
54
What happens: calling a function
void swap( int a, int b) Main program calls function swap(Value1, Value2); Computer makes a new ‘frame’ for executing function swap The values of the actual parameters Value1 and Value2 are copied into the formal parameters in the new frame for the function Swap exchanges the values of value1 and value2 in the function frame Void return value: no value returned Variables used in main int value1 = 10; int value 2 = 15; swap( value1, value2) Variables used in swap b = 10; a = 15; Return Computer memory © Janice Regan, CMPT
55
What happens: calling a function
void swap( int a, int b) Main program calls function Computer makes a new ‘frame’ for executing function swap Value1 and Value2 are copied into the formal parameters in the new frame for the function Swap exchanges the values of value1 and value2 in the function frame Void return value: no value returned The function ‘frame’ for swap is destroyed Any changes to the values of variables in the function ‘frame’ are lost In the main program firstValue and secondValue still have their original values: They have not been swapped Variables used in main int value1 = 10; int value 2 = 15; swap( value1, value2) Computer memory © Janice Regan, CMPT
56
Consequences of what happens
The value of a parameter cannot be changed inside a function When the new frame is made the values of the actual parameters are copied into the formal parameters If the value of the formal parameter is changed in the function, only the value of the formal parameter in the new ‘frame’ is changed. When the new ‘frame’ is destroyed all record of what happened within the function is gone Since the change was made in the function frame of the calling function is not even aware that it happened © Janice Regan, CMPT
57
Passing variables by reference
So far we have been using the values of variables as parameters in our functions This is called passing arguments by value We have seen that when passing a variable by value it is not possible to change the value of that variable within the function In some applications we need to change the value of a variable within a function To do this we must pass the variable by reference Instead of using the variable as our parameter, we use a reference or pointer to the variable as our argument © Janice Regan, CMPT
58
Swap function; references
Consider a function to swap two values void swap( double& value1, double& value2) { double tmp; tmp = value1; value1 = value2; value2 = tmp; //The values in variables value1 and value2 have been //exchanged, since these values are direct references to //the actual variables in the calling function, the values in //the calling function are also changed } © Janice Regan, CMPT
59
What happens when you call a function: 1
Main program declares variables firstValue and secondValue and initializes their values to 123 and 345 Main program calls function swap(firstValue, secondValue); Variables used in main secondValue=34 firstValue=123 Computer memory © Janice Regan, CMPT
60
What happens: 2 Computer makes a new ‘frame’ for executing function swap Function swap has declaration void swap( double& value1, double& value2); Main program calls function swap(firstValue, secondValue); References to firstValue and secondValue are placed in the new frame In the new frame firstValue is referred to as value1 (corresponding formal parameter of the function swap) In the new frame secondValue is referred to as value2 Variables used in main firstValue=123 secondValue=345 Local variables used in fun1 value1 (reference to firstValue in main) value2 (reference to secondValue in main) Computer memory before swap © Janice Regan, CMPT
61
What happens: 3 In the function value1 and the value2 (value1=123, value2=456) are swapped While swapping the values referred to by value2 and value1 are changed. Therefore, the values of firstValue and secondValue in main are changed To swap the values in memory locations value1 and value2 tmp = value1; value1 = value2; value2 = tmp; Variables used in main firstValue=345 secondValue=123 Local variables used in fun1 value1 (reference to firstValue in main) a value2 (reference to secondValue in main) Computer memory after swap © Janice Regan, CMPT
62
What happens: 4 The frame created to execute the function swap is destroyed The values of variables firstValue and secondValue have been swapped Variables used in main firstValue=345 secondValue=123 Computer memory © Janice Regan, CMPT
63
Scope Variables with local scope are
Declared inside body of given function Not defined outside of the body of the given function Variables and constants with global scope are Declared outside of all functions (before the first function in the file) Usable by all functions in the file Variables with block scope are Declared inside a block (between {} ) within a function Usable only within that block (between the {} ) © Janice Regan, CMPT
64
Block Scope A variable declared in a block (within a pair of { }) only exists in that block If you do not declare variables at the start of your program you may declare them within a pair of { } nested inside your function In this case the variables will not exist outside the { } in the remainder of the function If you try to use the variable outside the { } it will not exist and your program will fail © Janice Regan, CMPT
65
Local Variable declarations
You must declare local variables used in the function DO NOT declare formal parameters of the function within the function. This will create a new variable that “hides” the formal parameter passed into the function Initialize the local variables in your function DO NOT initialize actual parameters within your function. The value of the parameter you supply when you call the function will be replaced by the value in your initialization © Janice Regan, CMPT
66
Local Scope: Avoid a common problem
A variable X declared inside the main function is not the same variable as a variable X declared in another function The variable X defined in the main function is local to the main function, and only exists in the main function The variable X defined in the other function exists only in the other function, it is not accessible in the main function. IT IS NOT THE SAME VARIABLE X as the X in the main function © Janice Regan, CMPT
67
SCOPE: Global Variables
Global variables are variables that are declared outside any function (including main) can be accessed within any function in the file It is poor programming practice to use global variables They can be changed in any function in the file. This makes debugging programs that use global variables difficult and time consuming. They should not be used as parameters (arguments) of functions or as variables whose values are returned by functions. © Janice Regan, CMPT
68
SCOPE: Global Constants
Global constants are useful they are declared outside any function (including main) can be accessed within any function in the file are useful when a constant is needed in several functions do not change during the execution of the problem so they do not make debugging more difficult should not be used as parameters (arguments) of functions or as variables whose values are returned by functions. © Janice Regan, CMPT
69
Why use prototypes You may see programs where all the functions are defined before the main program and no prototypes are used In projects that are not very small this becomes difficult and error prone To make this work every function must be defined before any other function that calls it The ordering of functions can be time consuming The ordering of functions is not always possible\ © Janice Regan, CMPT
70
More reasons Correction of errors and modification of or addition to the code become more time consuming If you do not remember the name of the function it can be hard to locate, you must look through the definitions rather than just a list of prototypes © Janice Regan, CMPT
71
Functions: Class coding standard
Prototypes should be given before the main program (global scope) All user defined function definitions should follow the main program Local variables in each function should be declared/initialized at the start of the function (after the { that starts the function body) Block scope variables used in one block inside a larger function may be declared /initialized at the start of that block (after the { that begins the block they are defined in, or in the for statement) © Janice Regan, CMPT
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.