Reputation: 347606
Why does the following code NOT give an error, nor any type of a warning about an implicit conversion?
std::wstring str = L"hi";
if(str[0] == 'h')
cout<<"strange"<<endl;
The proper normal code is:
std::wstring str = L"hi";
if(str[0] == L'h')
cout<<"strange"<<endl;
Compiler: visual studio 2005
Warning level: level 4 (highest)
Upvotes: 1
Views: 933
Reputation: 180303
It's hard to say for sure why the compiler doesn't give a warning. They may do so for any reason, and should do so when the code is dubious. An error would be misplaced, though, as the code is technically correct.
In this case, my assumption is that the compiler doesn't emit a warning because the compiler uses a Unicode wchar_t
and an ISO-8859-1 char. The Unicode subset U+0000 to U+00FF equals ISO 8859-1 chars 0-FF. Thus, every char has the same numerical value as its corresponding wchar_t. As a result, wchar_t('a')==L'a'
.
Upvotes: 0
Reputation: 56123
Why does the following code NOT give an error ...
Isn't it because C++ allows implicit conversions? For example, isn't the following also legal:
if (str[0] == 104) //C++ allows various implicit type conversions
... nor any type of a warning about an implicit conversion?
That question is compiler-specific: which compiler are you using? There's probably a compiler option that affects what types of warnings you get from the compiler.
Upvotes: 2
Reputation: 248289
It doesn't give a warning because the comparison is valid. In general, you can always compare integral types, they just get promoted to wider types as needed.
And I'm pretty sure some compilers would issue a warning about this. Which one are you using? (In any case, warnings are compiler-specific, and they're not required to warn about this or anything else)
Upvotes: 7