Josh Susa February 2016

Range checking for my remove function in c++

So I have a method in c++ that takes an array and removes a certain number of values in the array. The method removes the range of values from the starting value all the way up to but not including the end value. void dynamic_array::remove(int start, int end) {

The only problem I'm having is with the range checking. So I've set up a way to check to make sure the start and end values are not in the incorrect places however whenever I test the code, it appears that it doesn't catch the range exception. Here's the code that's supposed to check the exception:

if (not (0 <= ((start <= (end < size))))){
        throw exception(SUBSCRIPT_RANGE_EXCEPTION);
    }

Answers


David van rijn February 2016

you cannot use the notation 1 < x < 2 in c++ (or most languages). So you have to do each comparison separately. ie. (1<x) && (x<2) (brackets not really necessary here).

If you are interested, you actually can use the notation, but it means something different than you might think. It means that you first compare 1<x which gives either true (1) or zero(0) and then you compare this 1 or 0 with two.


Sam Varshavchik February 2016

C++ does not work this way. The result of a single logical comparison is a boolean value. For example, the first comparison:

end < size

If this comparison is true, the result becomes a true value, which is for all practical purposes is 1. So, your expression now becomes, for all practical purposes:

if (not (0 <= ((start <= 1)))){

Which is already pretty much nonsensical, not to mention that there isn't a not operator in C++. Things pretty much roll downhill, from that point on.

You just need to make two logical comparisons: start < end, and end <= size. If you spend a few moments to think about it, you would realize this is all you need:

if (!(start < end && end <= size))


AchmadJP February 2016

It should be written

if(!(0 <= start && start <= end && end < size)){
    throw exception
}

As i know, C++ can't understand the way you write it.

Post Status

Asked in February 2016
Viewed 3,902 times
Voted 9
Answered 3 times

Search




Leave an answer