Albert G Lieu
Albert G Lieu

Reputation: 911

weird behavior caused by parenthesis () in c++

It is quite confusing that () caused unexpected behavior. I thought there is no difference in c++ that () is also used to group an expression. It seems that I am wrong in the following example. Could you explain how this happened?

Example 1 In this example, everything seems to work fine. It returns a correctly.

#include <iostream>
using namespace std;

int main(void) {
    string s = "abcd";
    string ret = "";
    int i = 0;
    ret = ret + "<b>" + s[i];
    cout << ret << endl;
}

Example 2 The only difference from example one is that a pair of () is added in ret = ret + "<b>" + s[i];. Then it runs successfully, but nothing has been returned in my local IDE, on leetcode web, it even throws an error Char 30: runtime error: index 97 out of bounds for type 'const char [4]' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:24:30

#include <iostream>
using namespace std;

int main(void) {
    string s = "abcd";
    string ret = "";
    int i = 0;
    ret = ret + ("<b>" + s[i]);
    cout << ret << endl;
}

Example 3 This example behaves like example 2. Nothing has been returned.

#include <iostream>
using namespace std;

int main(void) {
    string s = "abcd";
    string ret = "";
    int i = 0;
    ret += "<b>" + s[i];
    cout << ret << endl;
}

Upvotes: 1

Views: 131

Answers (1)

Dexus
Dexus

Reputation: 45

string literals automatically turn into pointers in some circumstances (all array types do this).

so when you have

string s = "";

s + "test";

this actually calls the operator+(string&, char*) that neatly copies and appends the characters from char* to string until the \0 character (strings usually end with \0 to signify end of string).

but when you do

string a = "a";

"test" + a[0];

you call operator+(char*, char) which adds the numerical value of char to the char*, which shifts where char* is pointing to by 97 bytes (97 is the numerical representation of character a in this case).

alternatively you could write:

"test"[a[0]]

which would have the exact same effect.

Upvotes: 1

Related Questions