In Stroustrup's book, the chapter 5 drill has a small program where you insert selections that have purposeful errors in order to better understand error handling. One of the inserts is as follows:
vector<char> v(5); for (int i=0; i<=v.size(); ++i) ; cout << "Success!\n";
Placed into the larger code, it looks like this:
#include "std_lib_facilities.h"
int main()
try {
vector<char> v(5);
for (int i=0; i<=v.size(); ++i) ;
cout << "Success!\n";
return 0;
}
catch (exception& e){
cerr<<"error: "<<e.what()<<'\n';
return 1;
}
catch (...){
cerr<<"Oops: unknown exception!\n";
return 2;
}
I can fix the code just fine. To fix it, I remove the improper semicolon in the middle of the for statement, and I ostensibly change the <= to a < operator in the for statement so it doesn't result in a range error. This compiles and prints 5 "Success!" to the terminal.
The problem is that if I modify the program to retain the range error in order to see how that error would be handled, I still don't get an exception. If, for example, I simply remove the semicolon and leave the <= as is, it prints "Success!" 6 times. If I even make it do so for i<=v.size()+10, it still prints out "Success!" many times.
My understanding from Stroustrup is that this should not be how this is handled. It should throw an exception because <= makes it read 6 indexes for vector v and the 6th index should be out of range.
Can anyone help me understand why this program is not throwing an exception for the range error and not having any sort of problem?
I am using g++ as my compiler on a fresh install of Ubuntu 18.04 that I installed for the express purpose of learning to code. No special compiler arguments are used. Just "g++ -o NAME CODE.cpp".