#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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With