Lab 9 - DBC

Examples

Using Assertions in C++ - lecture example

assert is used as follows:

    assert( vec != NULL );
    assert( vec->size() > 1 );

assert checks a given condition - if the condition is true it does nothing however if the condition is false
an "Assertion failed" error message is shown like the following and the program stops executing at the line where the assertion failed

Assertion failed: vec != NULL, file C:\cpp\AssertEx1.cpp, line 13

Run and test the example below with NULL and vector sizes of 0, 1 and more than 1 to understand how assert works

#include <assert.h>
#include <iostream>
#include <vector>
using namespace std;
 
/**
 * Precondition: Vector should not be NULL
 *               Vector should have more than 1 element
 * Postcondition: Elements of a vec are return in sorted
 *                order
 */
void sort(vector<int> *vec) {
    assert( vec != NULL );
    assert( vec->size() > 1 );
    cout << "sorting vector...." << endl;
}
 
int main() {
    //code to test the first assert
    vector<int> *v = NULL;
 
    //code to test the second assert
    /*
    vector<int> *v = new vector<int>();
    v->push_back(1);
    */
 
    //code to test the second assert
    /*
    vector<int> *v = new vector<int>();
    v->push_back(1);
    v->push_back(7);
    */
 
    sort(v);
}

Exercises

Exercise 1: Write a pre and post conditions for the following method which compares two arrays and returns true if they are the same else returns false if they are different.
Use assertions to test the pre conditions.

bool compare(int a[], int asize, int b[], int bsize) {
     //what assertions will be used to test the preconditions
     //need the implementation code
}

Exercise 2: Write the pre and post conditions for the following method which converts an array into a vector and returns it. The Vector will have same elements and size as that of that array.
Use assertions to test the pre conditions and the post conditions.

vector<int> convertToVector(int a[], int asize) {
     //what assertions will be used to test the preconditions
     //need the implementation code
     //what assertions should be used to test post conditions
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License