0
int main(){
    string s = "";
    s += 1;// if I do s = s + 1 code doesn't compile
    cout<<"Hello world"+10<<endl;
    cout<<s<<endl;
}

Why it prints d and random character. I try to think it as string is a char* then if I do str + 10 then it points to the 10 pos. I am not sure I am correct or not.

  • And that is `d`, what do you think it should be? I'm not seeing the problem. – john Sep 22 '22 at 14:00
  • 1
    `"Hello world"` is a string literal and **decays** to `const char*`. Then you add `10` to that pointer. Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO posts for this. For example, [Why can you add an integer to a string literal?](https://stackoverflow.com/questions/25299156/why-can-you-add-an-integer-to-a-string-literal) or [C++ Adding String Literal to Char Literal](https://stackoverflow.com/questions/5705956/c-adding-string-literal-to-char-literal) – Jason Sep 22 '22 at 14:01
  • 1
    The random char is from `cout< – 001 Sep 22 '22 at 14:01
  • `std::string` is not an array. It encapsulates one. It is rather unfortunate that `s += 1;` compiles :/ – 463035818_is_not_an_ai Sep 22 '22 at 14:01
  • @john yes it does. I suppose thats what the question is all about – 463035818_is_not_an_ai Sep 22 '22 at 14:02
  • @463035818_is_not_a_number I saw your comment, how does it compile? – john Sep 22 '22 at 14:02
  • 2
    @john Because `operator +=` can take a `char` and the constant `1` can be converted to a `char`. – NathanOliver Sep 22 '22 at 14:03
  • @NathanOliver Of course, very unfortunate. you'll be telling me that `s += false;` compiles as well. – john Sep 22 '22 at 14:03
  • @john [It does indeed](http://coliru.stacked-crooked.com/a/014f706ffa32bc24) – NathanOliver Sep 22 '22 at 14:05
  • @john Should do, that conversion is legal too :( – Paul Sanders Sep 22 '22 at 14:06
  • what are you actually asking? The title is about `cout<<"Hello world"+10< – 463035818_is_not_an_ai Sep 22 '22 at 14:06
  • related https://stackoverflow.com/questions/26186107/my-code-works-now-but-why-adding-0-to-a-string – 463035818_is_not_an_ai Sep 22 '22 at 14:06
  • Another problem is that the text of the question keeps changing. – john Sep 22 '22 at 14:06
  • There was no reason to reopen the question. There are plenty of dupes for this. – Jason Sep 22 '22 at 14:08
  • @OP Undefined behavior means anything can happen including but not limited to the program giving your expcected output. But never rely on the ouptut of a program that has UB. The program may just crash. Also, refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). **Don't try random stuff with c++**. It may lead to UB. – Jason Sep 22 '22 at 14:12

0 Answers0