Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Functions.

Similar presentations


Presentation on theme: "Chapter 3 Functions."— Presentation transcript:

1 Chapter 3 Functions

2 3.3 Functions – why?

3 3.3 What is a function? Functions are like building blocks
They allow complicated programs to be divided into manageable pieces The function has (or may have) a result (returning value function) The function has (or may have) an effect (void function) A function is just a separate part of a code that can be used at (almost) any time to evaluate something, to do something, or both. We identify a function by its name. The name of a function is subject to the same restrictions as a variable's name.

4 3.3 What is a function? Two types of functions
Predefined Functions (by c++ environment) User defined Functions (by the programmer) To use any predefined function, you should include its library to your program. When you want a particular function to perform its actions and/or evaluations, you need to invoke it. The function invocation (call) is a special instruction in the C++ language. The invocation has to specify the name of the function being invoked (always), the parameters that the function should use (if needed) and how to use the result evaluated by the function (if any).

5 Updated by: Malak Abdullah
Predefined Functions In algebra, a function is defined as a rule or correspondence between values, called the function’s arguments, and the unique value of the function associated with the arguments If f(x) = 2x + 5, then f(1) = 7 f(2) = 9 f(3) = 11 1, 2, and 3 are arguments 7, 9, and 11 are the corresponding values

6 Predefined Functions (cont'd.)
Updated by: Malak Abdullah Predefined Functions (cont'd.) Some of the predefined mathematical functions are: sqrt(x) pow(x, y) floor(x) Predefined functions are organized into separate libraries I/O functions are in iostream header Math functions are in cmath header

7 Predefined Functions (cont'd.)
Updated by: Malak Abdullah Predefined Functions (cont'd.) pow(x,y) calculates xy pow(2.0, 3.0) = 8.0 Returns a value of type double x and y are the parameters (or arguments) The function has two parameters (at least one of them is doble or float) pow(2 , 3 ) some compilers consider this as error sqrt(x) calculates the nonnegative square root of x, for x >= 0.0 sqrt(2.25) is 1.5 Type double

8 Predefined Functions (cont'd.)
Updated by: Malak Abdullah Predefined Functions (cont'd.) The floor function floor(x) calculates largest whole number not greater than x floor(48.79) is 48.0 Type double Has only one parameter

9 Predefined Functions (continued)

10 Predefined Functions (continued)

11 Void & Returning value functions
The sqrt function will find and return the square root for the variable x value (returning value function) Note: to use sqrt, you should include cmath library. The swap function will swap between the value of the variables x and y (void function)

12 3.3 Why do we need functions?
Functions facilitate the creation of programs: Large and complex programs written using functions. Library functions are used by developer. Functions enable developers to divide a problem (and also a code) into smaller parts. A smaller code is easier to write, to test, to maintain and to understand. If the code you’ve written is too long to fit on one screen, consider dividing it into functions. It's easier to control a herd of small and well-defined functions than one large portion of code that you can't see at a glance. Having a set of well written and well tested functions lets the developer construct the code using ready-made blocks. This method of dividing the problem is known as decomposition.

13 3.3 Why do we need functions?
Two possible approaches can be used during decomposition: The top-down approach (when you try to define the most general functions first and then you divide them into simpler and more specialized ones). The bottom-up approach (when you start your work by creating a set of narrowly defined and highly specialized functions, and then assembling them into more complex structures).

14 Function declaration Each function is characterized by the following traits: Name Parameters, the number of parameters and their data types Data type of result  The part of the code that specifies all these elements is known as the function declaration (function prototype). The compiler must know the function declaration to enable it to properly interpret the invocations of the function. A function declaration says nothing about what the function does exactly. That information is provided by the function body, which is a separate part of the code, enclosed in brackets. A function declaration enriched with a function body forms the so-called function definition.

15 3.3 Introduction to functions
Example: write a function that can evaluate the second power of any float number. square would be quite a good name for the function; of course, we can call it in many different ways, e.g. sqr, SecondPowerOf or even JohnDoe (although it’s probably not a good idea, is it?) functions need one parameter: the value which will be raised to the power of 2; x will be a good name for the parameter, although not very original; the result type is float (like the parameter) Note that the first float specifies the type of the result, while the second is the type of the parameter.

16 3.3 First function Transforming a declaration into a definition requires us to add a body. The body also replaces the semicolon that ends the declaration. The function body doesn't end with a semicolon..

17 3.3 First function The function body contains:
A declaration of the result variable; the variable will be used inside the function and only inside the function it’s neither visible nor accessible in any other part of your code; The result variable will be assigned the value of the parameter x multiplied by itself; this is the simplest and fastest method of raising a number to the power of 2 return: this instruction is responsible for two important actions: it indicates which value is returned(provided) as the function result it terminates the execution of the function.

18 3.3 First function A value-returning function is used in an assignment or in an output statement Heading: first four properties above Example: float square(float x) Formal Parameter: variable declared in the heading Example: x Actual Parameter: variable or expression listed in a call to a function Example: z = square(9)  the actual parameter is 9

19 3.3 First function To make use of our first function and make it a part of a complete, runnable program see the following code. 

20 3.3 First function The parameters defined within the function are called formal parameters. float square(float x) The values actually transferred to the function (thus existing outside the function) are called actual parameters. square(arg); The function invocation is just the name of the function being invoked along with the values transferred (passed) into the function as actual parameters. For our example, we’ve declared a variable named arg and assigned it the value of 2.0. Next, we’ve invoked the square function, delivering the arg variable as its argument (the actual parameter). The result of the function is then sent to the screen and displayed as part of the message saying “The second power of 2 is 4”.

21 Value-Returning Functions
Heading Formal Parameters Actual Parameters

22 3.3 First function Is it possible to place the square function after the main function and not before? Yes, it is, but don't forget that the compiler must be aware of all the traits of the invoked function. Therefore, you have to put the function prototype before the first function invocation.

23 you can omit the formal parameter's name in the function prototype.
3.3 First function you can omit the formal parameter's name in the function prototype.

24 Syntax: Actual Parameter List
Updated by: Malak Abdullah Syntax: Actual Parameter List The syntax of the actual parameter list is: Formal parameter list can be empty: A call to a value-returning function with an empty formal parameter list is:

25 3.4 Declaring and defining functions

26 3.4 Declaring functions A function declaration is intended to inform a compiler about the function's name, its return type and type of the parameters (if any). A general form of function prototype is : return_type: describes the type of result returned (delivered) by the function. you can use any of the C++ types as a return_type, including a very special type named void. a function of type void returns no result at all; we can say that such a function may have an effect but definitely has no result;

27 3.4 Declaring functions (Prototype)
function_name: Is an identifier which names the function and distinguishes it from all other functions  (note: you can have more than one function of the same name, in contrast to variables; this is called overloading and we’re going to tell you about it soon). parameters_list:  (you have to!) is a comma-separated list of “type name” pairs enclosed in parentheses, where each of the names may be omitted; the list may be empty but the parentheses must still be there; you can emphasize the fact that your function has no parameters by putting the word void inside the parentheses, as follows: void fun(void); The declaration ends with a semicolon which must not be omitted.

28 3.4 Declaring functions (Prototype)
void fun(void); This declaration describes a function named fun which doesn't return a result and has no parameters; here’s an example of two equivalent function declarations: int func(int number); int func(int); In this context, the name of the parameter (number) means nothing to the compiler and it completely ignores it; it's not an argument against specifying the parameter's name in the declarations as it could be very useful for people trying to understand your code

29 3.4 Declaring functions Although each of the elements of the parameter list resembles the syntax of a variable declaration, you're not allowed to declare more than one parameter name at the same time int x, y; // this is not allowed in the parameter but you have to use the following if you want to declare two (or more) function parameters: void fun(int x, int y);

30 3.4 Defining functions A function definition specifies the code to be executed on each function invocation. It differs from the declaration in the fact that a semicolon is replaced by a body containing a sequence of declarations and/or instructions.

31 3.4 Defining functions If the return_type is void, the body may not contain the return instruction, but if it’s used with void function, it has to have the following form: void fun() { …… return; }  Note: there’s no value after the return (obviously, a void function isn’t able to return any value). It’s assumed that the return statement is implicitly executed within the void function's body just before the closing bracket. You don't have to write it there explicitly.

32 3.4 Defining functions If the return_type is not void, the body must contain at least one return statement specifying the value of the function's result. You can’t leave a function's body without specifying the result's value. Any value you intend the function body to return must have a type compatible with the type specified as the function type. You can use as many return statements as you need to effectively implement your algorithm.

33 3.4 Example functions Write a function to greet a user who will run our program. Use “Greet” as the name for that function. The new function should have no result and no parameters.

34 Example

35 Value-Returning Functions: Some Peculiarity

36 Value-Returning Functions: Some Peculiarity (cont'd.)

37 Value-Returning Functions: Some Peculiarity (cont'd.)

38 Example: Palindrome Number
A nonnegative integer is a palindrome if it reads forward and backward in the same way Examples: 5, 44,

39 3.4 Example functions Write a program that asks a user for the size of his/her ego and responds with an adequate greeting. The size of the ego is measured in meters.

40 3.4 Example functions Write a function its task is to convert a temperature value expressed in Fahrenheit to Celsius. Using the following formula: [°C] = ([°F] − 32) × 5 ⁄ 9

41 The formula embedded inside the FahrenheitToCelsius function
3.4 Example functions The formula embedded inside the FahrenheitToCelsius  function The TestTheFunction is designed to produce clear and legible output allowing testers to check the correctness of the function.

42 3.4 Example functions Test the function by forcing it to evaluate results for some characteristic values by using the TestTheFunction function. We expect the program to produce the following output: Fahrenheit 32 corresponds to 0 Centigrade Fahrenheit 212 corresponds to 100 Centigrade Fahrenheit 451 corresponds to Centigrade.

43 Flow of Execution Execution always begins at the first statement in the function main Other functions are executed only when they are called Function prototypes appear before any function definition The compiler translates these first The compiler can then correctly translate a function call

44 Flow of Execution (cont'd.)
A function call results in transfer of control to the first statement in the body of the called function After the last statement of a function is executed, control is passed back to the point immediately following the function call A value-returning function returns a value After executing the function the returned value replaces the function call statement

45

46

47

48

49 3.4. The invocation syntax - supplement
A C++ function may: return a value when it has a type name in front of its name or it doesn’t have the type name there (in this case the function is considered as returning an int value); such a function has a result and may have an effect, too return nothing when the void keyword is in front of its name; such a function doesn't have a result and we can expect that it has an effect.

50 3.4. The invocation syntax - supplement
These two kinds of functions differ in: The way they use the return statement. The returned value.   Note that: The only acceptable form of the VoidFunctioninvocation is: voidFunction(2); The NonVoidFunction can be invoked in the following two ways:  value = NonVoidFunction(2); NonVoidFunction(2); It means that any non-void function's result may be honored by the invoker (the former) and assigned to a variable, or used in any other way, or may be ignored by the invoker (the latter) and just forgotten immediately after the return from the function.

51 3.4 Activities Lab 3.4.7 (1) Old problems - new methods: functions [B]
Lab (2) One step further: finding length of months [B] Lab (3) Second step further: finding day of year [B] Lab (4) Third step further - counting days [B] Lab (5) A foretaste of system programming - obtaining current date [B] Lab (6) Prime numbers - how to find them? [B]

52 3.5 Transferring data to and from functions

53 Scope of an Identifier The scope of an identifier refers to where in the program an identifier is accessible Local identifier: identifiers declared within a function (or block) Global identifier: identifiers declared outside of every function definition C++ does not allow nested functions The definition of one function cannot be included in the body of another function

54

55 Scope of an Identifier (continued)
Some compilers initialize global variables to default values The operator :: is called the scope resolution operator By using the scope resolution operator A global variable declared before the definition of a function (block) can be accessed by the function (or block) even if the function (or block) has an identifier with the same name as the variable

56

57

58

59

60

61 Global Variables, Named Constants, and Side Effects
Using global variables has side effects A function that uses global variables is not independent If more than one function uses the same global variable and something goes wrong It is difficult to find what went wrong and where Problems caused in one area of the program may appear to be from another area Global variables allow functions to get and to provide data of any kind. If a function modifies any global variable that isn’t using any other mechanism of transferring data, we say that this function has a side effect. Global named constants have no side effects

62 3.5 Side effects

63 3.5 Side effects The globvar  is a global variable. Its declaration is not contained in any function. The func function increments the globvar upon every invocation. globvar is used to count func's executions. The main function makes use of globvar variable too, although it doesn't modify the variable's value. For this reason, we assume that the main  function doesn't cause side effects.

64 Parameters Any function needs to have the ability to communicate with its environment. It must be able to receive data (numbers, texts, etc.), process it and share the results. Two kinds of communication : transferring data to a function using actual parameters whose values are assigned to formal parameters (call by reference). transferring data from a function using the function's result; note that only one value may be transferred by such means because the syntax of the return  statement allows you to specify only one value (call by value).

65 Parameters (continued)
Value parameter: a formal parameter that receives a copy of the content of corresponding actual parameter Reference parameter: a formal parameter that receives the location (memory address) of the corresponding actual parameter

66 3.5 Passing parameters by value
The actual parameter's values are sent to the function. The parameters travel to the function's body and we don't expect them to return from there. Following is a simple experiment showing if a function is able to change the value of its parameter.

67 3.5 Passing parameters by value
2 param 1 var

68 3.5 Passing parameters by value
The AmIAbleToChangeMyParameter function increments its parameter's value. It also reports it to the user. Is the modified value visible outside the function? In other words: does the formal parameter's change reflect the actual parameter's value?  By running the code it produce the following output: var = I have got: 1 I'm about to give back: var = 1  As you can see, the formal parameter's value doesn't replace the actual parameter's value upon return from the function. We can say that the actual parameter has a one-way ticket: it transports a value to the function and doesn't take it up to the invoker. This way of communication is based on transferring a value from the invoker to the function. And that’s why this method is called passing parameters by value.

69 3.5. Passing parameters by reference
The C++ language doesn’t just offer one method for passing parameters. The second method is called passing by reference and allows functions to affect an actual parameter's values. To pass any parameters by reference, announce it while declaring the function. Seethe following example:

70 3.5. Passing parameters by reference
2 var param

71 3.5. Passing parameters by reference
It looks very similar to the previous example. But the difference caused by the & sign being placed in front of the parameter's name. This difference is very important, which radically changes the function's behavior. type name – the name parameter is passed by value type &name – the name parameter is passed by reference

72 3.5. Passing parameters by reference
When a parameter is passed by reference it means that a formal parameter is just a synonym of an actual parameter. Every modification made into a formal parameter immediately affects an associated actual parameter. We can informally say that parameters passed by reference have return tickets and bring their modified values back to the invoker. As you may suspect, the code will produce the following output: var = I have got: 1 I'm about to give back: var = 2

73 Reference Variables as Parameters
If a formal parameter is a reference parameter It receives the memory address of the corresponding actual parameter A reference parameter stores the address of the corresponding actual parameter During program execution to manipulate data The address stored in the reference parameter directs it to the memory space of the corresponding actual parameter

74 Reference Variables as Parameters (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Reference Variables as Parameters (continued) Reference parameters can: Pass one or more values from a function Change the value of the actual parameter Reference parameters are useful in three situations: Returning more than one value Changing the actual parameter When passing the address would save memory space and time

75 3.5 Passing parameters by reference
We do the selection of the passing method for each parameter individually. You can mix parameters of both kinds. Use the “passing by value” if you don't need to share the function's results using the parameter's values, and use “passing by reference” in all other cases. See the following example:

76 3.5 Passing parameters by reference
main MixedStyle var1 1 2 var2 bref 1 bval

77 3.5 Passing parameters by reference
The MixedStyles function assigns its second parameter with an incremented value of its first parameter. This means that the former parameter is passed by value, while the latter is passed by reference. The program produces the following output: var1 = 1, var2 = 2

78

79 3.5 Passing parameters by reference
The “passing by reference” method has one important and obvious limitation. If a parameter is declared as passed by reference (so it is preceded by the & sign) its corresponding actual parameter must be a variable. An actual parameter referring to a “passed by value” formal parameter may be an expression in general, so we can use not only a variable but also a literal, or even a function invocation's result. We say this limitation is “obvious” because the function can’t place a value in something other than a variable. It cannot assign a new value to a literal, or force an expression to change its result. See the following example:

80 3.5 Passing parameters by reference
All the following invocations are permitted: ByVal(i); ByVal(i + 2); ByVal(intfun(0)); If you want to modify the invocations to take advantage of the ByRef function, you can only use the first one. All the others will cause a compilation error.

81 Static and Automatic Variables
Automatic variable: memory is allocated at block entry and deallocated at block exit By default, variables declared within a block are automatic variables Static variable: memory remains allocated as long as the program executes Variables declared outside of any block are static variables Declare a static variable within a block by using the reserved word static

82 Static and Automatic Variables (continued)
The syntax for declaring a static variable is: The statement static int x; declares x to be a static variable of the type int Static variables declared within a block are local to the block Their scope is the same as any other local identifier of that block

83

84 3.6 Default parameters

85 3.6 Parameters 

86 3.6 Default parameters According to our example most of the users require only one greeting at the same time. This may mean that we could use the following form of greeting more often than others: NewGreet("Good morning", 1);  We may just want to omit the “1”, hoping that the function will be smart enough to guess what we're going to do. This can be done but we have to inform the function that some of the invocations will not specify all the expected parameters, and indicate which values should be used instead of the absent ones. This mechanism is called “default parameters”. We can modify the formal parameter's declaration by using a phrase: = value

87 NewGreet(string greet, int repeats = 1)
3.6 Default parameters To signal that we want the compiler to assume the default value for the parameter when we omit it during the invocation we declare the function in the following way: NewGreet(string greet, int repeats = 1) The compiler will treat the one-parameter invocations like this one: NewGreet("Hello");   As if they were (explicitly) written as follows: NewGreet("Hello", 1);

88 3.6 Default parameters The output will be: Hello Hello Good morning Hi
Note that the explicitly specified parameter value invalidates the default value.

89 3.6 Default parameters It is possible to have more than one default parameter in one function. If the function has more than one default parameter the order of parameters is very important (in contrast to regular, non-default parameters which may be in any order). The rule is the non-default parameters must be coded before the default ones; the compiler won't be able to identify the parameters otherwise. All default parameters must be the rightmost parameters of the function

90 3.6 Default parameters It is possible to have more than one default parameter in one function.

91 3.6 Default parameters If more than one parameter is declared with a default value and at least one actual parameter is specified in the invocation, the actual parameters are assigned to their formal counterparts in the same order in which they are listed in the function declaration. This means that you are not allowed to use the default value for the first parameter and specify an explicit value for the second.

92 3.6 Default parameters Examples of illegal function prototypes with default parameters:

93 3.6 Default parameters Consider the following prototype: Assume:
a, b are int, ch is char, d is double Examples of legal calls: Examples of illegal calls:

94

95 3.6 Activities Lab (1) Modifying function argument's value - how to do it? [A]

96 3.8 Overloaded functions

97 3.8 Different tools for different tasks
It is not allowed to have a variable and a function of the same name. It is allowed to have more than one function of the same name. We may want to have different tools of the same name used for different purposes. For example, we need a function to find the larger of two float numbers.

98 3.8 Different tools for different tasks
To find the largest of the a and b variables, we may invoke this function : x = max(a,b); To  find the largest of the a, b and c variables, we may invoke this function : x = max(max(a,b),c);

99 3.8 Different tools for different tasks
To find the maximum of three float values we may write a new function and name it like the old one: max. This name perfectly illustrates the function's role and purpose.

100 3.8 How it works? The mechanism that allows us to have more than one function of a certain name is called overloading. There is one, important limitation: all the overloaded functions must be clearly distinguishable to the compiler. The compiler cannot hesitate over which of the overloaded variants need to be used in a particular part of the code. for example in max functions if the invocation contains three actual parameters, the second variant is chosen. If there are two parameters, the compiler uses the first variant. Any other variant of the invocation is considered an error.

101 3.8 How it works? Circumstances the compiler take into consideration when choosing the one target function: The number of parameters: for example, if there are three overloaded functions with (respectively) two, three and four parameters, and the invocation specifies two parameters, only the first of the functions may be used as a target (this function is called 'the best candidate') The parameters' types: if there’s more than one function with the same number of parameters, the target function is selected on the basis of the parameters' type conformity. Note: the return type is not taken into consideration when the compiler is looking for the best candidate for a certain invocation. This should be obvious to you if you remember that the return value of any typed function may be ignored. In this sense, two functions which differ only in the return type are indistinguishable to the compiler. This means that the following snippet is wrong:   int fnc(int a) {      return a; }   void fnc(int a) { }

102 3.8 How to find the best candidate?
The number of different data types in the C++ language is significant, so the mechanism responsible for finding the best candidate has to use some simplifications so as not to force developers to create a separate function for each different data type. For example: Which of these two overloaded functions is the best candidate for the invocation? it’s the first one, with the int x parameter declaration.

103 3.8 How to find the best candidate?
Change the example: Which of the functions is the best candidate now?  There is no good candidate for the invocation.

104 3.8 How to find the best candidate?
The literal 1.0 is not of type float, it's of type double. The C++ language compiler tries to promote the types if there is no exact fit as in our example: a float is not a double.  Unfortunately the direction of this type of promotion goes from less precise to more precise, not vice versa. It means, that any float can be promoted to double, but no double can be promoted (or rather degraded) to float. In this situation, the compiler will inform you that it is unable to find the best candidate and the compilations will fail.

105 3.8 How to find the best candidate?
There is two choices: Writing the third instance of the PlayWithNumber with one parameter of type double. Convince the compiler that your literal is of type float; by adding the suffix f to the number, as follows: PlayWithNumber(1.0f);


Download ppt "Chapter 3 Functions."

Similar presentations


Ads by Google