0

In the below code, I have initialised an empty string 'a' and now I am arbitrarily trying to print any value out of it. Please help me understand why it does not show any error and prints garbage value instead!

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

int main() {
    string a = "";
    for(int i=0;i<10;i++)
        cout<<a[i];
     for(int i=0;i<10;i++)
        cout<<(int)a[i];
    cout<<"|";
    cout<<"\n"<<a.size();
}
  • 6
    i crossed a red light, even though it is forbidden, I dont understand why I am not in jail – 463035818_is_not_an_ai Apr 22 '20 at 15:02
  • 2
    maybe I should explain: You shall not access the string out-of-bounds. Period. Thats all there is to know. If you expect to get an error, then you are wrong. Use the `at` method if you want bounds checking – 463035818_is_not_an_ai Apr 22 '20 at 15:04
  • [Undefined Behaviour](https://en.cppreference.com/w/cpp/language/ub) can result in *anything*. A crash or exception is not guaranteed. *Nothing* is guaranteed. It may even appear to work or the compiler may choose to omit all your code or *whatever* else you can think of. Just don't invoke UB. – Jesper Juhl Apr 22 '20 at 15:15

0 Answers0