Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.

Similar presentations


Presentation on theme: "C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq."— Presentation transcript:

1 C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq

2 Content 2  C++ Modules  Function syntax  Function parameters and return types  Defining functions within programs  Using and invoking function  Function prototypes  Function, file, and block scope  Function signature  Argument coercion  Function Overloading  Reference parameters  Passing arguments (pass-by-value, pass-by-reference)  Common errors

3 Modules  Blocks of codes with an independent functionality.  Written and tested separately.  Combined to form a complete program.  Modules either control or general:  Control Called “Main” each program include only one control module.  General Perform manipulations on data e.g. calculation, print, read and validation. 3

4 C++ Modules  All Modules in C++ are called “functions”  called methods or procedures in other languages.  Functions can be  Programmer-defined.  Built-in: pow, sqrt,.. etc.  Advantage  make programs easier to write, test, debug and maintain. 4

5 Functions Syntax 5 ReturnType FctName(Parameter List) { action1; action2;.. actionN; return value ; } Function Header Function Body 32 1 1 2

6 Function Name and Return Type  Function name follows rules of naming identifiers as variables and constants.  Function return ONLY one value.  Function return types:  Built-in data types.  User-defined data types.  Nothing is returned by using keyword void. 6 int f1(Parameter List) { return value ; } int f1(Parameter List) { return value ; } void f2(Parameter List) { return; } void f2(Parameter List) { return; } void f2(Parameter List) { } void f2(Parameter List) { }

7 Function Parameters  Provide the communication links between the main program and its functions.  Parameters declared in the function header within parenthesis.  Either have a single, multiple parameters or have no parameters.  List of a parameters are separated by commas.  Each parameter must be defined as follows: DataType parameterName 7 char f1(int x, int y) { return value ; } char f1(int x, int y) { return value ; }

8 Problem Write a program that asks the user for the exam grade and prints a message indicating if the user has passed the exam or not. Can you solve the problem using functions ? 8 #include using namespace std; int main() { int grade; cout<<"Enter your grade:\n"; cin>>grade; if (grade>60) cout<<"You passed"; else cout<<“You failed"; return 0; } #include using namespace std; int main() { int grade; cout<<"Enter your grade:\n"; cin>>grade; if (grade>60) cout<<"You passed"; else cout<<“You failed"; return 0; }

9 1- Selecting Functions  Divide the program into tasks:  Read student grade.  Print appropriate message.  Naming functions:  Read_Grade  Display_Msg  main 9 Read_GradeDisplay_Msg main Fct

10 2-Analyzing Flow of Control 10 Read_Grade Display_Msg main Fct Start here Invoke to read input from user 1 2 Return the input read from the user 3 Invoke to display message AND send the grade returned by Read_Grade 4 Display message on screen AND return control to Main 5 return 0 ; 6

11 3-Defining Functions  For each function decide on:  Possible Parameter List  Possible Return Value int Read_Grade(){ } void Display_Message(int g){ } 11 Read_Grade Main Fct Invoke to read input from user Return the input read from the user Display_Msg Main Fct Invoke to display message AND send the grade returned by Read_Grade Display message on screen AND return control to Main

12 3-Defining Functions (cont.) 12 Read_GradeDisplay_Msg Main Fct #include using namespace std; int main() { int grade; cout<<"Enter your grade:\n"; cin>>grade; if (grade>60) cout<<"You passed"; else cout<<“You failed"; return 0; } #include using namespace std; int main() { int grade; cout<<"Enter your grade:\n"; cin>>grade; if (grade>60) cout<<"You passed"; else cout<<“You failed"; return 0; } Read_Grade Display_Msg

13 3-Defining Functions (cont.) 13 int Read_Grade() { int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade; return grade; } void Display_Msg(int g) { if (g>60) cout<<"You passed"; else cout<<“You failed"; } int Read_Grade() { int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade; return grade; } void Display_Msg(int g) { if (g>60) cout<<"You passed"; else cout<<“You failed"; } grade scope g scope

14 4-Using Functions 14 #include using namespace std; // ====== You Must Define your Modules before Main ====== int Read_Grade() { int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade; return grade; } void Display_Msg(int g) { if (g>60) cout<<"You passed"; else cout<<“You failed"; } // ====================== Main Fct ====================== int main() { // Invoke read module and store returned input // Invoke display module and pass the grade return 0; } #include using namespace std; // ====== You Must Define your Modules before Main ====== int Read_Grade() { int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade; return grade; } void Display_Msg(int g) { if (g>60) cout<<"You passed"; else cout<<“You failed"; } // ====================== Main Fct ====================== int main() { // Invoke read module and store returned input // Invoke display module and pass the grade return 0; }

15 4-Using Functions (cont.)  In our example, all invokations occur in main function.  Invoking C++ functions syntax:  Write function name followed by ().  Within ( ) passing values (arguments) to parameters. Functions could have No parameters  FunctionName() One or more parameters  FunctionName(v1,v2)  Capturing returned values Functions return type could be void  FunctionName() OR FunctionName(v1,v2) Non-void  must use returned value in expression. 15

16 4-Using Functions (cont.)  Capturing returned values  Non-void  must use returned value in expression  Function Read_grade() returns an int  int n = Read_Grade();  if ( Read_Grade() == 3 ) …… … …  cout << Read_Grade(); 16

17 4-Using Functions (cont.)  Each value passed in a function call is referred to as an Argument.  Arguments (Passed in a Function call) and parameters (defined in a function header) MUST match in:  Number  Order  Data types 17 void Display_Msg(int g) { if (g > 60) cout<<"You passed"; else cout<<“You failed"; } void Display_Msg(int g) { if (g > 60) cout<<"You passed"; else cout<<“You failed"; } int main() { Display_Msg(87); return 0; } int main() { Display_Msg(87); return 0; } Argument Parameter

18 Final Solution 18 #include using namespace std; // ====== You Must Define your Modules before Main ====== int Read_Grade() { int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade; return grade; } void Display_Msg(int g) { if (g>60) cout<<"You passed"; else cout<<“You failed"; } // ====================== Main Fct ====================== int main() { int n = Read_Grade(); // Invoke read function Display_Msg(n); // Invoke display function return 0; } #include using namespace std; // ====== You Must Define your Modules before Main ====== int Read_Grade() { int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade; return grade; } void Display_Msg(int g) { if (g>60) cout<<"You passed"; else cout<<“You failed"; } // ====================== Main Fct ====================== int main() { int n = Read_Grade(); // Invoke read function Display_Msg(n); // Invoke display function return 0; }

19 Using Library Functions  Need to know the points below to write invokation of built-in functions correctly:  Name of the function.  Number, type and order of parameters.  Type of return value if it has.  Header file.  Examples Header File Function call Example Value pow(x,y) pow(2,3) 8 setprecision(n) setprecision(2)<< 1.2345 1.23 19

20 Function Prototype  Consists of the function's return type, name and parameter list ( number, types and order of parameters).  Also called function declaration.  Usually placed at the top of the program to tell the compiler that the function exists.  Same as corresponding function header except that:  Parameter names are optional  Must end with a semicolon ; 20

21 Examples 21 int square( int x ) { return x * x; } void useLocal( void ) { int x = 25; cout << "\nlocal x is " << x << endl; x++; cout << "local x is " << x << endl; } void useLocal(); int square( int );

22 Compilation Error 22 #include using std::cin; using std::cout; using std::endl; int main() { int a = 10; cout << a << " squared: " << square( a ) << endl; return 0; } int square( int x ) { return x * x; } Error: function undeclared before use 'square': identifier not found

23 Solution -1 23 #include using std::cin; using std::cout; using std::endl; int square( int x ) { return x * x; } int main() { int a = 10; cout << a << " squared: " << square( a ) << endl; return 0; }

24 Solution -2 24 #include using std::cin; using std::cout; using std::endl; int square( int ); // prototype for function square int main() { int a = 10; cout << a << " squared: " << square( a ) << endl; return 0; } int square( int x ) { return x * x; }

25 Empty Parameter Lists  Specified by writing either void or nothing at all in parentheses. int sum(); OR int sum(void); 25

26 Scope  Identifiers  Variable or object.  Function.  Scope of Identifier  Portion of the program where an identifier can be used.  Types of scopes for an identifier:  Function scope.  File scope.  Block scope. 26

27 File Scope  For an identifier declared outside any function or class  Identifier is “known” and can be used in all functions from the point at which it is declared until the end of the file.  Examples  Global variables, function definitions and function prototypes placed outside a function all have file scope. 27

28 Function Scope  Can be used anywhere in the function in which they appear.  Cannot be referenced outside the function body.  Examples  Local variables and function parameters. 28

29 Block Scope  Blocks are defined by the beginning left brace ( { ) and the terminating right brace ( } ).  Identifiers declared inside a block have block scope  Block scope begins at the identifier’s declaration.  Block scope ends at the terminating right brace (}) of the block in which the identifier is declared. 29

30 30 #include using std::cout; using std::endl; int x = 1; // global variable int main() { int x = 5; // local variable to main cout << "local x in main's outer scope is " << x << endl; { // start new scope int x = 7; // hides x in outer scope cout << "local x in main's inner scope is " << x << endl; } // end new scope cout << "local x in main's outer scope is " << x << endl; return 0; } File Scope (defined outside any class or function) Function / Outer Block Scope (can be used only inside the outer block defined in Main) Function / Inner Block Scope (can be used only inside the inner block defined in Main)

31 Function Signature  The portion of a function prototype that includes the name of the function and the types of parameters.  Does not specify the function’s return type.  Functions in the same scope must have unique signatures. 31 int square( int ); Function Signature Function Prototype

32 Compilation Error -1 32 #include using std::cin; using std::cout; using std::endl; int square( int x ) { return x * x; } void square( int x) { cout<< x * x; } int main() { return 0; } // end main Two functions in the global(file) scope They have the same signature: square(int) This results in a compilation error: 'square' : redefinition

33 Compilation Error -2 33 #include using std::cin; using std::cout; using std::endl; class Num { int square( int x ) { return x * x; } void square( int x) { cout<< x * x; } }; int main() { return 0; // indicate successful termination } // end main Two functions in the class scope They have the same signature: square(int) This results in a compilation error 'Num::square' : redefinition

34 Compilation Error -3  Arguments (in function call) and parameters (in function header) must match in Number, Order, and Data Types. 34 #include using namespace std; int boxVolume( int length, int width, int height ) { return length * width * height; } int main() { cout<< boxVolume(); // Error#1: 'boxVolume' : function does not take 0 arguments cout<< boxVolume(10); // Error#2: 'boxVolume' : function does not take 1 argument cout<< boxVolume(10,5); // Error#3: 'boxVolume' : function does not take 2 arguments cout<< boxVolume(10,5,2); return 0; }

35 Argument Coercion  Arguments (in function call) and parameters (in function header) must match in Number, Order, and Data Types.  Promotion/Demotion may occur when the type of a function argument does not match the specified parameter type. 35

36 1- Argument Demotion 36 #include using namespace std; int boxVolume( int length, int width, int height ) ; int main() { cout<< boxVolume(10.5,5.7,2.4); return 0; } int boxVolume( int length, int width, int height ) { return length * width * height; } Warning: 'argument' : conversion from 'double' to 'int', possible loss of data

37 2- Argument Promotion 37 #include using namespace std; void boxVolume( double length, double width, double height ) ; int main() { boxVolume(10,5,2); return 0; } void boxVolume(double length, double width, double height ) { cout<< length * width * height; } No Warning is issued when promotion of arguments occurs

38 3- Return Type Demotion 38 #include using namespace std; double boxVolume( double length, double width, double height ) ; int main() { int r = boxVolume(10.5,5.7,2.3); return 0; } double boxVolume(double length, double width, double height ) { return length * width * height; } warning : conversion from 'double' to 'int', possible loss of data

39 4- Return Type Promotion 39 #include using namespace std; int boxVolume( int length, int width, int height ) ; int main() { double r = boxVolume(10,5,2); return 0; } int boxVolume(int length, int width, int height ) { return length * width * height; } No Warning is issued when promotion of return values occurs

40 Function Overloading  Creating several functions of the same name that perform similar tasks, but on different data types.  Overloaded functions have:  Same name.  Different signature.  Compiler selects proper function to execute based on number, types and order of arguments in the function call. 40

41 41 #include using std::cout; using std::endl; // function square for int values int square( int x ) { cout << "square of integer " << x << " is "; return x * x; } // function square for double values double square( double y ) { cout << "square of double " << y << " is "; return y * y; } int main() { cout << square( 7 ); // calls int version cout << endl; cout << square( 7.5 ); // calls double version cout << endl; return 0; }

42 42 #include using std::cout; using std::endl; // function multiply for two parameters int multi( int x, int y ) { return x * y; } // function multiply for one parameter int multi( int y ) { return y * 1; } int main() { cout << multi( 7,5 ); // calls 2 parameter version cout << endl; cout << multi( 7 ); // calls 1 parameter version cout << endl; return 0; }

43 43 #include using std::cout; using std::endl; // function multiply for two parameters int multi( int x, double y ) { return x * y; } // function multiply for two parameter but with different order double multi( double y, int x) { return y * x; } int main() { cout << multi( 7,5.5 ); // calls int,double version cout << endl; cout << multi( 7.5,3 ); // calls double,int version cout << endl; return 0; }

44 Reference Variables 44 // create an integer int a ; // Now create another name for the // same integer int& b = a ; //OR Int &b = a ; // create an integer int a ; // Now create another name for the // same integer int& b = a ; //OR Int &b = a ; grab memory for an integer and labels it as "a" "b" is just another label for the same memory a b b is a "reference". int& means "make a label to reference an integer" a and b are synonyms for the same thing

45 Reference Variables (cont.)  Can be used as aliases for other variables  An alias is simply another name for the original variable  All operations supposedly performed on the alias (i.e., the reference) are actually performed on the original variable  Must be initialized in their declarations  Cannot be reassigned afterward  Example int count = 1; int &cRef = count; cRef++; 45 1 count 1 cRef 2 count cRef

46 46 #include using std::cout; using std::endl; int main() { int x = 3; int &y = x; // y refers to (is an alias for) x cout << "x = " << x << endl << "y = " << y << endl; y = 7; // actually modifies x cout << "x = " << x << endl << "y = " << y << endl; return 0; // indicates successful termination } // end main x = 3 y = 3 x = 7 y = 7 #include using std::cout; using std::endl; int main() { int x = 3; int &y; // Error: y must be initialized cout << "x = " << x << endl << "y = " << y << endl; y = 7; cout << "x = " << x << endl << "y = " << y << endl; return 0; } Example #1 Example #2

47 Passing Arguments  Two ways to pass arguments to functions  Pass-by-value A copy of the argument’s value is passed to the called function Changes to the copy do not affect the original variable’s value in the caller Prevents accidental side effects of functions  Pass-by-reference Gives called function the ability to access and modify the caller’s argument data directly 47

48 Reference Parameter  An alias for its corresponding argument in a function call  & placed after the parameter type in the function prototype and function header  Example void squareByReference( int &numberRef ) ;  Parameter name in the body of the called function actually refers to the original variable in the calling function 48

49 Pass By Value 49 #include using std::cout; using std::endl; int squareByValue( int ); // function prototype (value pass) int main() { int x = 2; // demonstrate squareByValue cout << "x = " << x << " before squareByValue\n"; cout << "Value returned by squareByValue: " << squareByValue( x ) << endl; cout << "x = " << x << " after squareByValue\n" << endl; return 0; } int squareByValue( int number ) { return number *= number; // caller's argument not modified } 2 x 2 number

50 Pass By Reference 50 #include using std::cout; using std::endl; int squareByReference( int& ); // function prototype (value pass) int main() { int z = 4; // demonstrate squareByReference cout << "z = " << z << " before squareByReference" << endl; squareByReference( z ); cout << "z = " << z << " after squareByReference" << endl; return 0; } void squareByReference( int &numberRef ) { numberRef *= numberRef; // caller's argument modified } 4 z numberRef

51 Common Errors  Compilation errors  Declaring function has parameters of the same type as char a,b instead of char a, char b.  Invoking function before it is defined, e.g. when f1 invokes f2, f2 must be defined before f1.  Attempting to use a function that has no return value in an expression.  Two functions in the same scope have the same signature.  Mismatching function header with function call OR function header with function prototype in the number, type and order of parameters and arguments. 51


Download ppt "C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq."

Similar presentations


Ads by Google