jeudi 24 juin 2021

When is the assert ( ) expression evaluated in a scope?

I was trying to understand the assert() macro in C++ and I am confused as to when the assert statement is checked for its validity. I created a class Pyramid where I wanted to check if the Class attributes are positive and so I created a try() -> catch() exception handling first and if I enter a negative value for instantiating a Pyramid Object, it throws the error( along with the printData() also being evaluated)

However is I go for assert() also by putting a statement caught=false in caught() { } the, neither the expression std::cout<<errorText nor the printData() gets evaluated and the program just throws an Assertion "caught" failed. error.

Can someone please explain how is the control executed when we put an assert() statement in the scope and why std::cout<<errorText nor the printData() are not getting evaluated at all? The code is as below:

#include <stdexcept>
#include <iostream>
#include<string>
using namespace std;

class Pyramid
{
private:
    int length;
    int width;
    int height;
    float volume;

public:
    Pyramid(int l, int w, int h) : length(l), width(w), height(h)
    {
        volume = (1.0f / 3) * length * width * height;
    }

    void printData() const
    {
        std::cout << "\nLength : " << length
                  << "\nWidth : " << width
                  << "\nHeight : " << height
                  << "\nVolume : " << volume;
    }
    int Length() const
    {
        return length;
    }
    int Height() const
    {
        return height;
    }
    int Width() const
    {
        return width;
    }
    float Volume() const
    {
        return volume;
    }
};

int main()
{

    bool caught{true};
    try
    {   //Initialize Pyramid
        Pyramid pyramid( -11, 2, 3);

        //Print Check Pyramid Attributes 
        pyramid.printData();

        //Check for validity of attributes
        if (pyramid.Length() <= 0 || pyramid.Width() <= 0 || pyramid.Height() <= 0)
            throw std::string("\nAttributes cannot be zero or negative");
    }
    catch (std::string errorText)
    {
        std::cout << errorText;
        caught = false;
    }

    assert(caught);

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire