Reputation: 247
#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?
Upvotes: 7
Views: 1982
Reputation: 119382
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.
Upvotes: 4