2
#include <iostream>
using namespace std;

int main() {
    // your code goes here
    string g = "12345";
    cout << g[10] << endl; // Prints an empty character
    
    return 0;
}

Reference: https://ideone.com/rpCWm2

This surprisingly works and doesn't throw an error! Can somebody explain how this is happening? Thank you!

  • 1
    Yes, here is a perfect explanation: [Why does this simple program result in "puppies puppies puppies" to the console?](https://stackoverflow.com/questions/56979248/why-does-this-simple-program-result-in-puppies-puppies-puppies-to-the-console)... It's undefined behaviour to access out of bounds, `std::string` has checked `at()` method if you need checks. – Quimby Nov 19 '21 at 01:58
  • 1
    tl;dr The C++ compiler is free to assume that certain behaviors, like array index out of bounds, do *not* happen in the code. So if such a thing does happen, then ex falso quodlibet *anything* can happen. It could print an empty character, it could print nothing, it could print "puppies" over and over again, or it could mine bitcoins for Elon Musk. Any of the above is a valid interpretation of the program you've written, according to the C++ standard. – Silvio Mayolo Nov 19 '21 at 02:02
  • Got it! Thanks a lot! – Gagan Ganapathy Nov 19 '21 at 02:21

1 Answers1

3
std::string g = "12345";
std::cout << g[10] << std::endl;

Your access is out-of-bounds, which makes it an undefined behaviour. Undefined behaviour can do anything, from running normally to crashing the program.

If you use the at() function instead(which does bound-checking), you will see that this will throw an std::out_of_range exception.

std::string g = "12345";
std::cout << g.at(10) << std::endl;