Shoeb Uddin
Shoeb Uddin

Reputation: 11

Assert function causes program to crash

I have used assert function to ensure that the first number input is between 1 and 7 (inclusive). However, when I execute the program and enter an invalid number, it causes the program to crash. So, how is the assert function being of any use here if that's the case?

Please correct my implementation where required.

Code:

#include <iostream>
#include <assert.h>

using namespace std;

int main() {
    int num;
    int n;
    int max;
    cout << "Please enter a number between 1 & 7 \n";
    cin >> num;
    assert(num >= 1 && num <= 7);
    for (int i = 0; i < num; i++) {
        cout << "Please enter number " << (i + 1) << ": ";
        cin >> n;
        if (i == 0) {
            max = n;
        }  
        max = (n > max) ? n : max;
    }
    cout << "The maxmum value is: " << max << endl;
    system("pause");
    return 0;
}

Upvotes: 1

Views: 1511

Answers (2)

bgoldst
bgoldst

Reputation: 35314

Assert is not what you want here. What you need is validation. Assertions are for debugging, for identifying completely invalid program states. The user entering invalid input is not invalid program state, it's just invalid user input.

To perform validation, you need an if-test. You will also need some code ready to handle the case of invalid user input. There's absolutely no way to prevent the user from providing invalid input (short of insanely aggressive dynamic validation where you capture keyboard events as they occur and prevent those keystrokes from translating into character input to your program, but now we're just getting ridiculous), so you need to react to it when it happens, say, by printing an error message and then asking for more input.

One way of doing this is as follows:

do {
    cin >> num;
    if (!(num >= 1 && num <= 7)) {
        cerr << "invalid number; must be between 1 and 7!" << endl;
        num = -1;
    }
} while (num == -1);

Just to expand on that point about assertions, they are supposed to make the program crash. An assertion failure means your code is broken and must be fixed before it can be used in real life. Assertion failures should never be triggered in production code; they simply aid in testing and catching bugs.

Upvotes: 2

user4490718
user4490718

Reputation:

What does the "crash" does? According to me, assert will abort the program execution, maybe as another value other than 0.

Upvotes: 0

Related Questions