See the behaviour of char
in case of a vector<char>
and a standalone char
:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> someInts = {2, 3, 1 + 5};
// I can perform operations ^^^^^ inside the braces in this case
// vector<char> someChars = {'a', 'b', 'r' + 'z'};
// But doing the same in case of char ^^^^^^^^^ gives an error
// However, it works for a standalone char
char ch = 'r' + 'z';
cout << ch;
// Value^^^is '∞' as expected
}
Uncommenting the vector<char>
line gives:
Error: narrowing conversion of '236' from 'int' to 'char' inside { }
This was the problem.
Then I read this documentation of List Initialization, and saw the following which might be related to this problem:
Narrowing conversions
list-initialization limits the allowed implicit conversions by prohibiting the following:
- many other reasons
- conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where source is a constant expression whose value can be stored exactly in the target type
It made me understand the error message (I guess), and I changed vector<char>
to vector<unsigned char>
and it worked:
vector<unsigned char> someChars = {'a', 'b', 'r' + 'z'};
for (char ch : someChars)
cout << '_' << ch;
Output:
_a_b_∞
So, my question is:
If signedness of
char
was the problem, how did the standalone version ofchar
work in that case? With reference to this thread on stackoverflow, how did the same compiler choosesigned char
forvector<char>
andunsigned char
forchar
?If my deduction of the problem is wrong, what is the correct reason behind this issue?