DM560, Introduction to Programming in C++

Sheet 3

Main concepts from the lecture in week 39:

Kind of errors:

  • Compile-time
  • Link-time
  • Run-time
  • Logic errors

Check your inputs:

  1. Function arguments
  2. Data from input (istream)
class Bad_area { };     // a class is a user defined type

int area ( int length , int width )
{
  if ( length <=0 || width <=0) throw Bad_area {};  // note the {} - a value
  return length * width ;
}

try {
  int z = area (x , y );
}
catch ( Bad_area ) {
  cerr << "oops! Error \n";
}
catch (...)
{
  cerr << "Some other exception\n";
}

Include <stdexcept> to have available the error class hierarchy

Debugging:

  • Use “sanity checks” (cerr, error, assert, -fsanitize)
  • post and pre-conditions to functions
  • to debug segfault: -g and gdb

Testing:

  • write functions to test the elements (functions) of your programs.

Performance:

  • Computation time: time, <chrono, -pg + gprof gmon.out > a.txt]
  • memory usage

Task 1 (in class)

Implement the area example with pre- and post-condition. Determine which inputs would satisfy the pre-condition but not the post-condition. Catch this type of error.

Task 2 (in class)

Using the following skeleton:

#include <iostream>
#include <stdexcept>

using namespace std;
int main() {
        try {
                return 0;
        }
        catch (exception e) {
                cerr << "error: " << e.what() << '\n';
                return 1;
        }
        catch (...) {
                cerr << "Oops: unknown exception!\n";
                return 2;
        }
}

try the following statements containing errors. Recognize the type of error and comment:

Cout << "Success!\n" ;
cout << "Success!\n;
cout << "Success " << !\n "
cout << success << '\n';
string res = 7; vector<int> v(10); v[5] = res; cout << " Success!\n " ;
vector<int> v(10); v(5) = 7; if (v(5)!=7) cout << " Success!\n " ;
if (cond) cout << " Success!\n " ; else cout << " Fail!\n " ;
bool c = false; if (c) cout << " Success!\n " ; else cout << " Fail!\n " ;
string s = " ape " ; boo c = " fool " <s; if (c) cout << " Success!\n " ;
string s = " ape " ; if (s== " fool " ) cout << " Success!\n " ;
string s = " ape " ; if (s== " fool " ) cout < " Success!\n " ;
string s = " ape " ; if (s+ " fool " ) cout < " Success!\n " ;
vector<char> v(5); for (int i=0; 0<v.size(); ++i) ; cout << " Success!\n " ;
vector<char> v(5); for (int i=0; i<=v.size(); ++i) ; cout << " Success!\n " ;
string s = " Success!\n " ; for (int i=0; i<6; ++i) cout << s[i];
if (true) then cout << " Success!\n " ; else cout << " Fail!\n " ;
int x = 2000; char c = x; if (c==2000) cout << " Success!\n " ;
string s = " Success!\n " ; for (int i=0; i<10; ++i) cout << s[i];
vector v(5); for (int i=0; i<=v.size(); ++i) ; cout << " Success!\n " ;
int i=0; int j = 9; while (i<10) ++j; if (j<i) cout << " Success!\n " ;
int x = 2; double d = 5/(x  2); if (d==2*x+0.5) cout << " Success!\n " ;
string<char> s = " Success!\n " ; for (int i=0; i<=10; ++i) cout << s[i];
int i=0; while (i<10) ++j; if (j<i) cout << " Success!\n " ;
int x = 4; double d = 5/(x  2); if (d=2*x+0.5) cout << " Success!\n " ;
cin << "Success!\n " ;

Tip: if you need the help of the compiler to recognize the errors, then it might be useful using the flag -Wfatal-errors that stops compilation as soon as the first compiler error is encountered.

Task 3

Review of Chapter 5.

  1. Name four major types of errors and briefly define each one.
  2. What kinds of errors can we ignore in student programs?
  3. What guarantees should every completed project offer?
  4. List three approaches we can take to eliminate errors in programs and produce acceptable software.
  5. Why do we hate debugging?
  6. What is a syntax error? Give five examples.
  7. What is a type error? Give five examples.
  8. What is a linker error? Give three examples.
  9. What is a logic error? Give three examples.
  10. List four potential sources of program errors discussed in the text.
  11. How do you know if a result is plausible? What techniques do you have to answer such questions?
  12. Compare and contrast having the caller of a function handle a run-time error vs. the called function’s handling the run-time error.
  13. Why is using exceptions a better idea than returning an “error value”?
  14. How do you test if an input operation succeeded?
  15. Describe the process of how exceptions are thrown and caught.
  16. Why, with a vector called v , is v[v.size()] a range error? What would be the result of calling this?
  17. Define pre-condition and post-condition; give an example (that is not the area() function from this chapter), preferably a computation that requires a loop.
  18. When would you not test a pre-condition?
  19. When would you not test a post-condition?
  20. What are the steps in debugging a program?
  21. Why does commenting help when debugging?
  22. How does testing differ from debugging?

Task 4

We have previously seen a program to calculate the results of quadratic equations.

We did not handled a problem, though: if $b2–4ac$ is less than zero, then the program will fail.

Revise your program to calculate $x$ for a quadratic equation. Create a function that prints out the roots of a quadratic equation, given a, b, c. When the program detects an equation with no real roots, have it print out a message. How do you know that your results are plausible? Can you check that they are correct?

Task 5

The following program takes in a temperature value in Celsius and converts it to Kelvin. This code has many errors in it. Find the errors, list them, and correct the code.

double ctok(double c)
{
int k = c + 273.15;
return int
}

int main()
{
	double c = 0;
	cin >> d;
	double k = ctok("c");
	Cout << k << '/n';
}

Absolute zero is the lowest temperature that can be reached; it is $–273.15^o$C, or $0$K. The above program, even when corrected, will produce erroneous results when given a temperature below this. Place a check that will produce an error if a temperature is given below $–273.15^o$C.

Handle the error first in the main program and then inside ctok.

Task 6

Read (day-of-the-week, value) pairs from standard input. For example:

Tuesday 23 
Friday 56 
Tuesday –3 
Thursday 99

Collect all values for each day of the week in a vector<int>. Write out the values of the seven day-of-the-week vectors. Print out the sum of the values in each vector. Ignore illegal days of the week, such as Funday, but accept common synonyms such as Mon and monday. Write out the number of rejected values.

Modify the program to write out an error if the result cannot be represented as an int.

Task 7

Write a program that performs as very simple calculator. Your calculator should be able to handle the four basic math operations - add, substract, multiply, and divide - on two input values. Your program should prompt the user to enter three arguments: two double values and a character to represent an operation. If the entry arguments are 35.6, 24.1 and ‘+’, the program output should be The sum of 35.6 and 24.1 is 59.7.