Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why an empty string can output index 0 element in C++

Tags:

c++

#include<iostream>
#include<string>

using std::string;
using std::cout;
using std::endl;

int main()
{
    string s;
    cout << s.size() << endl;
    cout << s[0] << endl;  //output empty line
    return 0;
}

As s is an empty string, why can it has an element s[0]? In my opinion, it should get a run time error. Is it a convention or anything else?

like image 497
kkwang Avatar asked Oct 11 '14 03:10

kkwang


1 Answers

There's a special rule that you can access s[n] where n is the length of s. The result is a null character (i.e. the value that results from value-initializing the character type) and attempting to modify it causes undefined behaviour.

like image 52
Brian Bi Avatar answered Sep 29 '22 09:09

Brian Bi