Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 3.16: Assertions and Program Correctness

Adapted from: “Object-Oriented Programming Using C++” by Ira Pohl (Addison- Wesley)

Program that demonstrates the ASSERT statement in C++

// Finding a minimum element in an array slice.
#include <iostream>
#include <assert.h>

using namespace std;

void order (int & p, int & q)
{
    int temp = p;
    if (p > q) {
        p = q;
        q = temp;
    }
}

int place_min(int a[], int size, int lb = 0)
{
    int i, min;
    assert(size >= 0);   // precondition

    for (i = lb; i < lb + size; ++i)
        order(a[lb], a[i + 1]);
    return a[lb];
}

int main()
{
    int a[9] = { 6, -9, 99, 3, -14, 9, -33, 8, 11 };

    cout << "Minimum = " << place_min(a, 3, 2) << endl;
    assert(a[2] <= a[3] && a[2] <= a[4]);   // postcondition
}

Compile and Execute the Program

The above program is compiled and run using Gnu Compiler Collection (g++):

import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + "Cpp_Code/Chapter_3_16_Assertions_and_Program_Correctness"
ch_dir_stat = os.chdir(code_dir)
build_command = os.system("g++ order.cpp -w -o order")
exec_status = os.system("./order")
Minimum = -14