Funky string concatenation

Some weird stuff is happening when I try and concatenate strings and chars.

For example, this is inside of a static member function:
1
2
3
4
5
6
7
  int id = 0;
  char cid = '0'+id; 
  std::string quit = "quit";
  quit = cid+quit;
  std::string request = cid+" data"+name; //A
  std::cout<<"Name: "<<name<<"\nCID: "<<cid<<std::endl;
  std::cout<<"---"<<request<<"---"<<std::endl;


This causes some weird stuff to happen. name and CID get printed as expected, but request gets printed as weird stuff. It looks to be pulling parts of strings from nearby functions and combining that with whatever is stored in name.

Changing line A to
 
   std::string request = cid+name+" data";


makes everything work as expected
Last edited on
operator+, operator-, etc are evaluated left to right. So subterm cid + " data" is evaluated first.

As you're adding a char (an int type) to a pointer (to the C null-terminated string " data"), it ends up as pointer arithmetic. You're moving the pointer (which is originally pointing at the string " data") to point 'cid' chars further on in memory.

You then add this random C string to the std::string name (at least I assume name is a std::string?)

When you use cid+name+" data" instead you're adding a char and a std::string first. std::string knows how to do that, returning a new temporary string which can be added to the C string " data".

Andy

p   = pointer world!
p-s = Hello pointer world!
e+p = world!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main() {
    const char msg[] = "Hello pointer world!";
  
    const char* p = msg + 6; // point to pointer!

    char s = '\x6';
    char e = '\x8';
  
    std::cout << "p   = " << p   << "\n";
    std::cout << "p-s = " << p-s << "\n";
    std::cout << "e+p = " << e+p << "\n";

    return 0;
}

Last edited on
Topic archived. No new replies allowed.