Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ms N Nashandi Dr SH Nggada Week 2 - Variables, types, expressions and functions Namibia University of Science and Technology.

Similar presentations


Presentation on theme: "Ms N Nashandi Dr SH Nggada Week 2 - Variables, types, expressions and functions Namibia University of Science and Technology."— Presentation transcript:

1 Ms N Nashandi Dr SH Nggada Week 2 - Variables, types, expressions and functions Namibia University of Science and Technology

2 Outline We shall be covering the following Primitive types in C++ Enumeration Data Types Declaration Assignment Operations Looping with Enumeration Types The typedef statement Namespaces string The string type Boolean expressions Logical expressions Exception handling Functions Namibia University of Science and Technology 21/14/2016Ms N Nashandi and Dr SH Nggada

3 Primitive types in C++ Almost all programming languages provide a set of primitive (built-in) data types. A primitive type is a data type where the values that it can represent have a very simple nature (a number, a character or a truth-value); The following are primitive data types available in C++: bool, char, int, float, double, void wchar_t 1/14/2016Ms N Nashandi and Dr SH Nggada3

4 Integer Types Integers types are as follows short: 16 bits int: 16 or 32 bits long, INT32: 32 bits INT64: 64bits Integer types are assumed signed, unless if you prefix them with the unsigned keyword You can use standard arithmetic and relational operations with these types (identical to C#) 1/14/2016Ms N Nashandi and Dr SH Nggada4

5 Floating-point Types C++ provides three floating-point object types float: 4 bytes double: 8 bytes long double: 10 bytes Identical to C# 1/14/2016Ms N Nashandi and Dr SH Nggada5

6 Variables A variable is a memory address where data can be stored and changed. Declaring a variable means specifying both its name and its data type. E:g int i; // i represent the variable name // int represent the datatype 1/14/2016Ms N Nashandi and Dr SH Nggada6

7 Variables(Cont.) In C++, variables can be declared just about anywhere in your code and can be used anywhere in the current block below the line where they are declared. Variables can be declared without being given a value. These uninitialized variables generally end up with a semi-random value based on whatever is in memory at the time and are the source of countless bugs. 1/14/2016Ms N Nashandi and Dr SH Nggada7

8 Casting Variables can be converted to other types by casting them. For example, a float can be cast to an int. C++ provides three ways of explicitly changing the type of a variable.  float myFloat = 3.14f;  int i1 = (int)myFloat; // method 1  int i2 = int(myFloat); // method 2  int i3 = static_cast (myFloat); // method 3 The resulting integer will be the value of the floating point number with the fractional part truncated 1/14/2016Ms N Nashandi and Dr SH Nggada8

9 Enumeration Data Types C++ allows the user to define a new simple data type by specifying: Its name and the values But not the operations.  The values that we specify for the data type must be legal identifiers  The syntax for declaring an enumeration type is: enum typeName{value1, value2,...}; 91/14/2016Ms N Nashandi and Dr SH Nggada

10 Declaration of Enumerated Types enum rainbowColors = { red, orange, yellow, green, blue, indigo, violate } Consider the colors of the rainbow as an enumerated type: enum rainbowColors = { red, orange, yellow, green, blue, indigo, violate } The identifiers between { } are called enumerators red < orange < yellow … The order of the declaration is significant red < orange < yellow … 101/14/2016Ms N Nashandi and Dr SH Nggada

11 Declaration of Enumerated Types Why are the following illegal declarations? enum grades{'A', 'B', 'C', 'D', 'F'}; enum places{1st, 2nd, 3rd, 4th}; 11 They do not have legal identifiers in the list What could you do to make them legal? enum grades{A, B, C, D, F}; enum places{first, second, third, fourth}; 1/14/2016Ms N Nashandi and Dr SH Nggada

12 Declaration of Enumerated Types As with the declaration of any object Specify the type name Followed by the objects of that type enum daysOfWeek { Sun, Mon, Tue,Wed, Thu, Fri, Sat } Given: enum daysOfWeek { Sun, Mon, Tue,Wed, Thu, Fri, Sat } Then we declare: daysOfWeek Today, payDay, dayOff; daysOfWeek Today, payDay, dayOff; 121/14/2016Ms N Nashandi and Dr SH Nggada

13 Assignment with Enumerated Types Once an enumerated variable has been declared It may be assigned an enumerated value Assignment statement works as expected payDay = Fri; // note no quotes // Fri is a value, a constant Enumerated variables may receive only values of that enumerated type 131/14/2016Ms N Nashandi and Dr SH Nggada

14 Operations on Enumerated Type Objects Comparison normal, OK in order of the enumeration definition I/O generally not possible to do directly can be sort of done, indirectly Used primarily for program control, branching, looping Possible to have functions return an enumerated type 141/14/2016Ms N Nashandi and Dr SH Nggada

15 Looping with Enumeration Types Use an enumerated type variable as the loop control variable of a for loop for (day = Mon; day (day + 1)) {... } 15 This works because the values are represented internally as integers 1/14/2016Ms N Nashandi and Dr SH Nggada

16 Functions with Enumerated Types Enumeration type can be passed as parameters to functions either by value or by reference. A function can return a value of the enumeration type. daysOfWeek nextDay (daysOfWeek d) { return (daysOfWeek) ((d + 1)%7); } daysOfWeek nextDay (daysOfWeek d) { return (daysOfWeek) ((d + 1)%7); } 161/14/2016Ms N Nashandi and Dr SH Nggada

17 typedef The typedef statement Syntax: typedef existing_type_name new_type_name; Example: typedef int Boolean; Does not really create a new type is a valuable tool for writing self-documenting programs 171/14/2016Ms N Nashandi and Dr SH Nggada

18 Namespaces Recall use of using namespace std; Namespace is another word for scope In C++ it is a mechanism programmer creates a "named scope" namespace std { int abs ( int );... } 181/14/2016Ms N Nashandi and Dr SH Nggada

19 Namespaces Identifiers within a namespace can be used outside the body of the declaration only if use scope resolution operator x = std::abs(y); a using declaration using std::abs; z = abs(q); a using directive using namespace std; p = abs(t); 19 Note the distinction between declaration and directive 1/14/2016Ms N Nashandi and Dr SH Nggada

20 Namespaces We usually place the using directive in global scope All blocks {... } then have identifiers available from the std namespace 201/14/2016Ms N Nashandi and Dr SH Nggada

21

22 string The string type We have used arrays of char to hold "string" information char name[30]; cin >> name; There are some problems with doing this There is no assignment statement strcpy (name, "Clyde"); Must use strcpy (name, "Clyde"); Cannot do comparisons with if (strcmp (s1, s2) == 0) … Must use if (strcmp (s1, s2) == 0) … #include For all these must use #include 221/14/2016Ms N Nashandi and Dr SH Nggada

23 string The string type C++ has a string type which bypasses all the problems we've encountered #include // note no.h Gain these capabilities by #include // note no.h Now we can use statements as shown: string name = "Clyde"; if (title1 < title2) … if (title1 < title2) … str1 = str1 + "Day"; str1 = str1 + "Day"; // assignment and concatenation // assignment and concatenation 231/14/2016Ms N Nashandi and Dr SH Nggada

24 string The string type Some functions are available string name, title; name = "Alexander"; cout << name.length()<<endl; cout << name.find('x') <<endl; cout << name.substr(1,3) <<endl; title = "Big Cheese"; title.swap(name); cout << name<<endl; string name, title; name = "Alexander"; cout << name.length()<<endl; cout << name.find('x') <<endl; cout << name.substr(1,3) <<endl; title = "Big Cheese"; title.swap(name); cout << name<<endl; 24 Guess what will be the output of these lines of code 1/14/2016Ms N Nashandi and Dr SH Nggada

25

26 Boolean and logical expressions A boolean expression is an expression that has relational and/or logical operators operating on boolean variables. A boolean expression evaluates to either true or false. Relational operators are: == is identical to != is not identical to < is less than <= is less than or equal to > is greater than >= is greater than or equal to 26 NOTE: Relational operators can operate on integers, floats, doubles and even strings (in a lexicographical fashion). 1/14/2016Ms N Nashandi and Dr SH Nggada

27 Boolean and logical expressions Logical operators are: ! Logical negation && logical AND || logical OR Logical operators operate on boolean variables or boolean expressions only. 271/14/2016Ms N Nashandi and Dr SH Nggada

28 Examples of Boolean expression: long int winning_lottery_number = 947423945645, your_ticket_number; bool is_a_winner; cout > your_ticket_number; is_a_winner = (your_ticket_number == winning_ticket_number); // can omit the parentheses cout << "Please tell me if I won! "; cout << "Output a 1 if I won, otherwise output a 0: "; cout << is_a_winner << endl; 281/14/2016Ms N Nashandi and Dr SH Nggada

29 Boolean and logical expressions Most C++ compilers will treat any nonzero number as true and will treat zero as false. Careless use of Boolean expressions can lead to unexpected results. For example, a student fails a course if his score is less than the class average, otherwise the student passes the course. Someone may write the following code: if ( ! score > average ) cout < < "You failed the course.\n"; else cout < < "You passed the course.\n"; 291/14/2016Ms N Nashandi and Dr SH Nggada

30 Boolean and logical expressions(Cont.) The person read the code(see slide 31) as saying: if it is not true that the score is higher than the average, then you failed the course, otherwise you passed the course. The above code will not cause problem during compilation, and it will also run without run-time error. However the code actually has a mistake. Suppose the score is 34 and the average is 63. The compiler applies the precedence rule and interprets the Boolean expression as the following: ( ! score ) > average 301/14/2016Ms N Nashandi and Dr SH Nggada

31 Boolean and logical expressions(Cont.) The codes on slide 32 turns out to evaluates to false for the following reasons. First because ! is a unary logical negation operator and the value of score is nonzero and so score is converted to true. Thus !score evaluates to false. The next operator > compares 2 numbers and so !score is converted to 0, and then this value is compared with 63. Since 0 is not greater than 63, the entire expression evaluates to false, and the output will be: You passed the course. 311/14/2016Ms N Nashandi and Dr SH Nggada

32 Boolean and logical expressions(Cont.) Of course the correct way is to use parentheses and write the above Boolean expression as follows: if ( ! (score > average) ) cout < < "You failed the course.\n"; else cout < < "You passed the course.\n"; 321/14/2016Ms N Nashandi and Dr SH Nggada

33 Boolean expressions Boolean expressions: An expression such as (a && b) is false if either a or b is false. Similarly an expression such as (a || b) is true if either a or b is true. 33 For further details refer to: Boolean expression. Retrieved from: http://cis.poly.edu/~mleung/CS1114/f07/ch02/bool_exp.htm 1/14/2016Ms N Nashandi and Dr SH Nggada

34

35 Exceptions Good program is stable and fault tolerant. In a good program, exceptional (“error”) situations must be handled. Exceptions are unusual/unexpected events They may require special processing Exception handler is part of the code that processes an exception Some examples for exceptions: EOF is reached while trying to read from a file Division by 0 is attempted (result is meaningless) Array subscript is out of range Bad input 1/14/2016Ms N Nashandi and Dr SH Nggada35

36 Exception Handling 1/14/2016Ms N Nashandi and Dr SH Nggada36

37 Exception Handling This kind of error detection and handling makes the program logic unclear. cannot be used to handle errors in constructors (because they don’t return a value). Because of these drawbacks, a new method to handle error situations (exceptions) is developed in C++. With exception handling, it is possible to separate the code needed for "normal" operation and for exception situations. 1/14/2016Ms N Nashandi and Dr SH Nggada37

38 Basics try: identifies a code block where exception can occur throw: causes an exception to be raised (thrown) catch: identifies a code block where the exception will be handled (caught) try { … throw an exception … } catch the exception 1/14/2016Ms N Nashandi and Dr SH Nggada38

39 Exception Handling: Sample Code (ExceptionSample1.cpp) Simple program to collect the height of people: cin >> height; try { if (height > 300) throw "height exceeds maximum"; if (height < 30) throw "height below minimum"; cout << "Person is " << ToInches(height) << "inches tall" << endl; } catch (const char msg[]) { cout << "Exception occured: " << msg << endl; } 1/14/2016Ms N Nashandi and Dr SH Nggada39

40 The fundamentals of exception handling The "normal" code is put in try block. It means that we "try to execute code" in the try block. If the system succeeds to run the code, everything is fine (execution goes in order from top to down; catch blocks are skipped). If something goes wrong when code of try block is executed, this code throws an exception object and stops executing the code of try block further. Another part of the code (the error handling part) catches the exception (object) and takes necessary actions needed in that error situation. After that, execution continues with the next statement following the catch blocks The exception object (thrown object) can contain information about the exception, so that the error handling part of the program can examine the reason and make appropriate actions. 1/14/2016Ms N Nashandi and Dr SH Nggada40

41 How it works int main() { int height; cin >> height; try { if (height > 300) throw "height exceeds maximum"; if (height < 30) throw "height below minimum"; cout << "Person is " <<ToInches(height) << "inches tall" << endl; } catch(const char msg[]) { cout << "Exception occured: "<< msg << endl; } cout << "Program Stops " << endl; return 0; } When an exception is thrown, the remaining code in the try block is skipped, just as in the case of the return statement in a function, and every auto object created after the try block is entered, is destroyed automatically The thrown object is caught by the catch block where the execution continues Then, the execution continues with the next statement after the catch block 1/14/2016Ms N Nashandi and Dr SH Nggada41

42 Catching Exceptions You must supply at least one catch block for a try block Otherwise compiler error (let's see it in ExceptionSample1.cpp). int main() { int height; cin >> height; try { if (height > 300) throw "height exceeds maximum"; if (height < 30) throw "height below minimum"; cout << "Person is " <<ToInches(height) << "inches tall" << endl; } //NO CATCH HERE – NOT ALLOWED return 0; } 1/14/2016Ms N Nashandi and Dr SH Nggada42

43 Catching Exceptions Catch blocks must immediately follow the try block without any program code between them. Otherwise, compiler error (let's see it in ExceptionSample1.cpp). int main() { int height; cin >> height; try { if (height > 300) throw "height exceeds maximum"; if (height < 30) throw "height below minimum"; cout << "Person is " <<ToInches(height) << "inches tall" << endl; } cout << "Wassup"; //no statements are allowed between try and catch catch(const char msg[]) { cout << "Exception occured: "<< msg << endl; } cout << "Program Stops " << endl; return 0; } 1/14/2016Ms N Nashandi and Dr SH Nggada43

44 Catching Exceptions Catch blocks will catch exceptions of the correct type that occur in the code in the immediately preceding try block, including the ones thrown by functions called within the try block. Let's see it in ExceptionSample1.cpp). int main() { int height; cin >> height; try { if (height > 300) throw "height exceeds maximum"; if (height < 30) throw "height below minimum"; cout << "Person is " <<ToInches(height) << "inches tall" << endl; } catch(const char msg[]) { cout << "Exception occured: "<< msg << endl; } cout << "Program Stops " << endl; return 0; } int ToInches (int cm) { if (cm == 100) throw "you are a winner!"; return cm/2.54; } 1/14/2016Ms N Nashandi and Dr SH Nggada44 Here, if height is 100 exception is thrown in ToInches function and caught in main. Output is: Exception occured: you are a winner! Program Stops

45 Catching Exceptions There can be more than one catch blocks. The one that will catch a particular exception is determined by the type of the object/value thrown (like overloaded functions). Let's see it in ExceptionSample2.cpp). try { if (height <= -1) throw 0; if (height > 300) throw "height exceeds maximum"; if (height < 30) throw "height below minimum"; cout << "Person is " <<ToInches(height) << "inches tall" << endl; } catch (int i) { cout << "Bad input: height cannot be less than " << i << endl; } catch(const char msg[]) { cout << "Exception occured: "<< msg << endl; } 1/14/2016Ms N Nashandi and Dr SH Nggada45 throw 0; is caught by catch (int i) String literal throw s are caught by catch(const char msg[]) You cannot have two catches with the same type in the same try-catch block – this would be a compiler error.

46 Process Terminates (Actually Your Program Crashes) If Exception is not Caught – Unhandled Exceptions 46 If an exception is not caught by any catch statement because there is no catch statement with a matching type, the special function terminate will be called. This function terminates the current process immediately showing an "Abnormal termination" or a similar error message. int main() { try { throw "error"; } catch (int i) { cout << "Why I dont catch anything? \n"; } 1/14/2016Ms N Nashandi and Dr SH Nggada

47 No Typecasting between throw and catch The type matching between the object thrown and caught is very strict. The parameter given in catch must be exactly the same as the type of the object/value thrown. No typecasting is done implicitly (there is no typecasting even between double and int) Let's see it in ExceptionSample3.cpp). 47 string s="yadda yadda"; cin >> input; try { if (input == 1) throw 1.1; if (input == 2) throw 2; if (input == 3) throw "bla bla"; if (input == 4) throw s; } catch (double i) { cout << "Double exception handler" << endl; } catch (int i) { cout << "Integer exception handler" << endl; } catch(const char msg[]) { cout<<"char array exception handler" <<endl; } catch(string s) { cout << "String exception handler" << endl; } Having a missing catch may cause a crash. For example, if we do not have catch (int i) and its block, and if the input is 2, catch with double parameter does not handle this case and program crashes. String literals (e.g. "ali veli") are considered as char pointers, not C++ strings. Thus thrown string literals always have to be caught by catch with char * or char [] parameters (catch with string parameters cannot catch them). 1/14/2016Ms N Nashandi and Dr SH Nggada

48 Nested tries Try-catch blocks can be nested. Each try block has its own catch blocks In case of nested try blocks: if an exception is thrown within an inner try block which is not followed by a catch block with the right type, the catch handlers for the outer try block(s) will be searched (starting with the closer try). When a matching catch is found, search finishes. If a matching catch is not found, then the program terminates with an error (unhandled exception case). 48 1/14/2016Ms N Nashandi and Dr SH Nggada

49 Nested tries – Example (see ExceptionSample4.cpp) 49 int height; string err="Input cannot be below 0"; try { cin >> height; try { if (height <= -1) throw err; if (height > 300) throw "height exceeds maximum"; if (height < 30) throw height; cout << "Person is " << ToInches(height) << " inches tall" << endl; } catch(const char msg[]) { cout << "Exception occured: " << msg << endl; } cout << "I am in the middle.\n" << endl; } catch (int i) { cout << "Exception occured: Height must be greater than "<<i<< endl; } The exception of type const char[ ] is caught by the catch block in the inner try block The exception of type int has no catch handler for exceptions of that type, so the the catch handler in the outer try block is executed The exception of type string has no catch iny any of the try blocks, so the program crashes if height is less than zero. This statement is executed if no exceptions are thrown or the thrown exception is caught before that 1/14/2016Ms N Nashandi and Dr SH Nggada

50 Catching exceptions If you want to catch any exception that is thrown in a try block, no matter the type of thrown object is, you specify this as: catch (...) { // code to handle any exception } This catch block must appear last if you have other catch blocks defined for the try block. Note that in this catch block, you do not know what type of exception has occured and cannot use a reference to an object 50 1/14/2016Ms N Nashandi and Dr SH Nggada

51 Example (see ExceptionSample4.cpp) 51 int height; string err="Input cannot be below 0"; try { cin >> height; try { if (height <= -1) throw err; if (height > 300) throw "height exceeds maximum"; if (height < 30) throw height; cout << "Person is " << ToInches(height) << " inches tall" << endl; } catch(const char msg[]) { cout << "Exception occured: " << msg << endl; } catch (int i) { cout << "Exception occured: Height must be greater than "<<i<< endl; } catch (...) { cout << "Houston we have a problem, but I do not know what it is :(\n"; } Previous example but now we have catch (...) to catch any unhandled exception, which is the string exception in our example case. 1/14/2016Ms N Nashandi and Dr SH Nggada

52 Basics of Exception Handling 52 1/14/2016Ms N Nashandi and Dr SH Nggada

53 53 1/14/2016Ms N Nashandi and Dr SH Nggada

54 54 Stack unwinding If exception is thrown in a try block (or in a function that is called from a try block or in a function that is called from a function that is called from a try block and so on), all local objects allocated from the stack after the try block was entered are released (go out of scope) and their destructors are called. This process is called stack unwinding. This process guarantees that when we try to recover from an error, there are no inconsistent data in the stack and there is no memory leak (again within the stack; we will discuss memory leak considerations in the heap for dynamically allocated memory later). 1/14/2016Ms N Nashandi and Dr SH Nggada

55 55 Stack unwinding Example int main() { //.... try { Aclass myA; f1(); //.... } //catch come here } void f1() { Bclass myB; f2(); //.... } void f2() { Cclass myC; //.... throw "Exception"; } If error occurs in the function f2, the destructors for objects myA, myB and myC are called and those objects are deleted from the stack in the reverse order of creation and before the exception is caught. Note that this would also return any dynamically allocated memory used in those objects (myA, myB, myC), through their properly implemented destructors. 1/14/2016Ms N Nashandi and Dr SH Nggada

56 Another example (problematic) Sometimes stack unwinding does not suffice since it does not return the dynamic memory to heap. try { int * myarr; myarr = new int [LARGECLASS]; Process(myarr); //suppose an exception is thrown in Process function } catch (...) { //Need to free the heap memory pointed by myarr //But there is a problem – cannot refer myarr cout << "Exception caught" << endl; } 56 1/14/2016Ms N Nashandi and Dr SH Nggada

57 Exception Handling as an Object Oriented Mechanism Exception handling is actually a pure object oriented mechanism You can throw objects of classes specifically designed for exception handling. You can also inherit subclasses from a base exception class and throw them. Now we will see these mechanisms via some examples. 57 1/14/2016Ms N Nashandi and Dr SH Nggada

58 Example: Division by zero handled via a user defined exception class - 1 // Class DivideByZeroException definition. // DivideByZeroException objects should be thrown by functions // upon detecting division-by-zero exceptions class DivideByZeroException { public: // constructor specifies default error message DivideByZeroException() : message( "attempted to divide by zero" ) {} //what returns the message char * what() {return message;} private: char * message; }; 58 1/14/2016Ms N Nashandi and Dr SH Nggada

59 Example: Division by zero handled via a user defined exception class - 2 // perform division and throw DivideByZeroException object if // divide-by-zero exception occurs double quotient( int numerator, int denominator ) { // throw DivideByZeroException if trying to divide by zero if ( denominator == 0 ) throw DivideByZeroException(); // generate and throw exception object // return division result return (double) numerator / denominator; } 59 1/14/2016Ms N Nashandi and Dr SH Nggada

60 Example: Division by zero handled via a user defined exception class - 3 int main() { //.... try { result = quotient( number1, number2); cout << "The quotient is: " << result << endl; } catch ( DivideByZeroException myException ) { cout << "Exception occurred: " << myException.what() << endl; } //.... } 60 See and run the full code at DividebyZeroException.cpp 1/14/2016Ms N Nashandi and Dr SH Nggada

61 Inheritance for Exception Classes We can use inheritance! Suppose MathException is the base class for several math exceptions. class MathException { public: MathException(char * m = "Unidentified Math Error") { message = new char [strlen(m)+1]; strcpy (message, m); } char * what() {return message;} protected: char * message; }; 61 Study Yourselves: Think of destructor and copy constructor here and consequences of having/not having them 1/14/2016Ms N Nashandi and Dr SH Nggada

62 Inheritance for Exception Classes We can use inheritance! Suppose MathException is the base class for several math exceptions. We can inherit several subclasses from it class DivideByZeroException : public MathException { public: DivideByZeroException () : MathException("attempted to divide by zero") {} }; class OverflowException : public MathException { public: OverflowException () : MathException("overflow detected") {} }; class RootOfNegativeException : public MathException { public: RootOfNegativeException () : MathException("you cannot calculate square root of negatives") {} }; 62 1/14/2016Ms N Nashandi and Dr SH Nggada

63 Inheritance for Exception Classes We can use inheritance! Suppose MathException is the base class for several math exceptions. We can inherit several subclasses from it and use to catch different type of exceptions Example: try { // code to throw exceptions here } catch (DivideByZeroException myEx) //catches DivideByZeroException objects only { /* catch code here */ } //specialized handler for divide by zero catch (OverflowException myEx) //catches OverflowException objects only { /* catch code here */ } //specialized handler for oveflow catch (MathException &myEx) //catches all other objects derived from MathException base class { /* catch code here */ } //generic handler The last catch may cause polymorphism (if the thrown object is of a derived class, e.g. RootOfNegativeException ) To avoid slicing it is better to use reference parameter here. 63 1/14/2016Ms N Nashandi and Dr SH Nggada

64 64/551/14/2016Ms N Nashandi and Dr SH Nggada

65 Introduction Divide and conquer Construct a program from smaller pieces or components Each piece more manageable than the original program The Top-down design approach 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 1/14/2016Ms N Nashandi and Dr SH Nggada65

66 Advantages of Functions Functions separate the concept (what is done) from the implementation (how it is done). Functions make programs easier to understand. Functions can be called several times in the same program, allowing the code to be reused. 1/14/2016Ms N Nashandi and Dr SH Nggada66

67 C++ function A C++ function or a subprogram is simply a chunk of C++ code that has: A descriptive function name, e.g. 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) 1/14/2016Ms N Nashandi and Dr SH Nggada67

68 C++ Function (cont.) C++ allows the use of both user-defined and Prepackaged(: from the standard library) functions Prepackaged functions (e.g., abs, ceil, rand, sqrt, etc.) are usually grouped into specialized libraries (e.g., iostream, stdlib, math, etc.) 1/14/2016Ms N Nashandi and Dr SH Nggada68

69 C++ (Prepackaged) Standard functions 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 library Character-manipulation functions are declared in library 1/14/2016Ms N Nashandi and Dr SH Nggada69

70 Declaration of functions In C++, you first declare a function to make it available for other code to use. If the function is used inside only a particular file, you generally declare and define the function in the source file. If the function is for use by other modules or files, you generally put the declaration in a header file and the definition in a source file. 1/14/2016Ms N Nashandi and Dr SH Nggada70

71 Math Library Function Perform common mathematical calculations Include the header file Functions called by writing functionName (argument); or functionName(argument1, argument2, …); Example cout << sqrt( 900.0 ); sqrt (square root) function The preceding statement would print 30 All functions in math library return a double 1/14/2016Ms N Nashandi and Dr SH Nggada71

72 Math Library function(Cont.) Function arguments can be Constants sqrt( 4 ); Variables sqrt( x ); Expressions sqrt( sqrt( x ) ) ; sqrt( 3 - 6x ); 1/14/2016Ms N Nashandi and Dr SH Nggada72

73 Example of Using Standard C++ Math Functions #include int main() { // Getting a double value double x; cout << "Please enter a real number: "; cin >> x; // Compute the ceiling and the floor of the real number cout << "The ceil(" << x << ") = " << ceil(x) << endl; cout << "The floor(" << x << ") = " << floor(x) << endl; return 0; } 1/14/2016Ms N Nashandi and Dr SH Nggada73

74 Difference between #include and #include ”filename” For #include "filename" the preprocessor searches in the same directory as the file containing the directive. This method is normally used to include programmer-defined header files. For #include the preprocessor searches in an implementation dependent manner, normally in search directories pre-designated by the compiler/IDE. This method is normally used to include standard library header files 1/14/2016Ms N Nashandi and Dr SH Nggada74

75 User-Defined C++ Functions 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 user-defined function) For example, the library does not include a standard function that allows users to round a real number to the i th digits, therefore, we must declare and implement this function ourselves 1/14/2016Ms N Nashandi and Dr SH Nggada75

76 How to define a C++ Function? function prototype Step #1 – declare the function prototype 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 1/14/2016Ms N Nashandi and Dr SH Nggada76

77 What is The Syntactic Structure of a C++ Function? A C++ function consists of two parts The function header, and The function body The function header has the following syntax ( ) ( ) The function body is simply a C++ code enclosed between { } 1/14/2016Ms N Nashandi and Dr SH Nggada77

78 Example of User-defined C++ Function double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; } 1/14/2016Ms N Nashandi and Dr SH Nggada78

79 Function Prototypes Function prototype contains Function name Parameters (number and data type) Return type ( void if returns nothing) Only needed if function definition after function call Prototype must match function definition Function prototype double maximum( double, double, double ); Definition double maximum( double x, double y, double z ) { … } 1/14/2016Ms N Nashandi and Dr SH Nggada79

80 Function prototypes (Cont.) The prototype gives a lot of information about the function. One, it tells it the return type. Two, it tells it how many parameters there are, and what their types are. The actual names of the parameter values (x, y and z in our example) can be left in or out of the prototype. Generally, leaving them out leaves you with the flexibility of renaming variables at will 1/14/2016Ms N Nashandi and Dr SH Nggada80

81 Function signature Part of prototype with name and parameters double maximum( double, double, double ); The function signature must be ended by a semicolon 1/14/2016Ms N Nashandi and Dr SH Nggada81 Function signature

82 Using Parameters Function Parameters come in three flavors: Value parameters Value parameters – which copy the values of the function arguments Reference parameters Reference parameters – which refer to the function arguments by other local names and have the ability to change the values of the referenced arguments Constant reference parameters Constant reference parameters – similar to the reference parameters but cannot change the values of the referenced arguments 1/14/2016Ms N Nashandi and Dr SH Nggada82

83 By Value(Cont.) This is what we use to declare in the function prototype or function header, e.g. int max (int x, int y); Here, parameters x and y are value parameters max(4, 7) When you call the max function as max(4, 7), the values 4 and 7 are copied to x and y respectively max (a, b), 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 max( a+b, b/2), 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! 1/14/2016Ms N Nashandi and Dr SH Nggada83

84 Calling by value Copy of data passed to function Changes to copy do not change original Prevent unwanted side effects 1/14/2016Ms N Nashandi and Dr SH Nggada84

85 By references Call by reference Function can directly access data Changes affect original 1/14/2016Ms N Nashandi and Dr SH Nggada85

86 passing parameters by references Example outputs 1. // passing parameters by reference 2. #include 3. using namespace std; 4. void duplicate (int& a, int& b, int& c) 5. { 6. a*=2; 7. b*=2; 8. c*=2; 9. } 10. int main () 11. { 12. int x=1, y=3, z=7; 13. duplicate (x, y, z); 14. cout << "x=" << x << ", y=" << y << ", z=" << z; 15. return 0; 16. } x=2, y=6, z=14 1/14/2016Ms N Nashandi and Dr SH Nggada86

87 passing parameters by references(Cont.) To gain access to its arguments, the function declares its parameters as references. In C++, references are indicated with an ampersand (&) following the parameter type, as in the parameters taken by duplicate in the example above. When a variable is passed by reference, what is passed is no longer a copy, but the variable itself, the variable identified by the function parameter, becomes somehow associated with the argument passed to the function, and any modification on their corresponding local variables within the function are reflected in the variables passed as arguments in the call. 1/14/2016Ms N Nashandi and Dr SH Nggada87

88 Constant Reference Parameters 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 It is a syntax error to pass constant values or expressions to the (const) reference parameters 1/14/2016Ms N Nashandi and Dr SH Nggada88

89 Building Your Libraries It is a good practice to build libraries to be used by you and your customers In order to build C++ libraries, you should be familiar with How to create header files to store function prototypes How to create implementation files to store function implementations How to include the header file to your program to use your user-defined functions 1/14/2016Ms N Nashandi and Dr SH Nggada89

90 C++ Header Files 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 prototypes with some comments about their purposes, their inputs, and outputs #endif compiler directive 1/14/2016Ms N Nashandi and Dr SH Nggada90

91 header file add.h: 123456789123456789 // This is start of the header guard. ADD_H can be any unique name. By convention, we use the name of the header file. #ifndef ADD_H #define ADD_H // This is the content of the.h file, which is where the declarations go int add(int x, int y); // function prototype for add.h -- don't forget the se micolon! // purpose -- to compute the sum of two given numbers // input -- two integers // output -- a sum of two numbers // This is the end of the header guard #endif 1/14/2016Ms N Nashandi and Dr SH Nggada91

92 main.cpp that includes add.h 2345678923456789 #include #include "add.h" int main() { using namespace std; cout << "The sum of 3 and 4 is " << add(3, 4) < < endl; return 0; } 1/14/2016Ms N Nashandi and Dr SH Nggada92

93 add.cpp implementation file int add(int x, int y) { return x + y; } 1/14/2016Ms N Nashandi and Dr SH Nggada93

94


Download ppt "Ms N Nashandi Dr SH Nggada Week 2 - Variables, types, expressions and functions Namibia University of Science and Technology."

Similar presentations


Ads by Google