Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting "number 0" to char before appending it

Why would I need to explicitly cast number 0 to char before appending it to string using string::operator+?

using namespace std;

int main()
{

    string s = "";
    s += 65; // no compile error
    s += (char)0; // requires explicit cast 
    //s += 0; // compile error
    return 0;
}

Update to clarify: My goal has been to append one byte (containing whatever value, including zero) to an existing array of bytes.

like image 437
B Faley Avatar asked Dec 18 '11 07:12

B Faley


Video Answer


2 Answers

Because s += 0 is ambiguous for the following overloaded operators of +=

string& operator+= ( const char* s );
string& operator+= ( char c );

0 for the first function means a NULL terminated string with first character set to NULL, and for the second function is a single character with value set to 0.

like image 86
saeedn Avatar answered Sep 18 '22 02:09

saeedn


It is because ONLY 0 can be implicitly converted into pointer type. No other integer can implicitly be converted into pointer type. In your case, 0 can be converted into const char* and char both. When it is converted into const char*, it becomes a null pointer.

So there is ambiguity as to which conversion should take place, as there are two overloads of operator+=, for each type of arguments: const char* and char.

But when you use non-zero integer, say 65, it cannot convert into const char*. So the only function it can call is one which takes char as argument, as 65 is converted into char.

like image 35
Nawaz Avatar answered Sep 18 '22 02:09

Nawaz