2

This code is showing error.

#include <bits/stdc++.h>

using namespace std;

int main() {
    string s;
    s="b"+"k"+"4";
    cout<<s<<endl;
    return 0; 
}

This code is working properly.

#include <bits/stdc++.h>

using namespace std;

int main() {
    string s;
    string s1 = "a";
    s=s1+"b"+"k"+"4";
    cout<<s<<endl;
    return 0; 
}

I don't know why this is happening, in both the cases i am using strings?

2 Answers2

3

With

s="b"+"k"+"4";

your literal strings will decay to pointers, and you will add those pointers together, and assign the result to s. That pointer addition will make no sense, there's no overloaded + operator function which takes two const char * arguments.

But with

s=s1+"b"+"k"+"4";

you start with a std::string object, for which there are overloaded + operator functions, which return a std::string object. It is in short something similar to

s=((s1+"b")+"k")+"4";

That is you have s1 + "b", which returns a temporary std::string which you then add "k" to, which returns a temporary std::string to which you add "4", which returns a temporary std::string which is assigned to s. Or with the temporary objects and functions calls explicitly used:

std::string t1 = operator+(s1, "b");
std::string t2 = operator+(t1, "k");
std::string t3 = operator+(t2, "4");
s = t3;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

The accepted answer is perfectly correct but i just thought it might be useful to show expression poisoning.

The technique is often called "infecting" or "poisoning" expressions. An expression library that makes extensive use of this is boost yap. The idea is to "infect" the left most expression with "stringy-ness" (pardon my french). An example

#include <iostream>
#include <string>

int main(int, char**){
    auto s = std::string("a") + "b" + "c";
    std::cout << "s = " << s << '\n';
    return 0;
}

Making the leftmost expression a string infects the entire expression forcing the compiler to lookup std::string operator+ which finds a right hand expression of char* which is exactly the operator we want.

systemcpro
  • 856
  • 1
  • 7
  • 15