views:

280

answers:

3

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)

+5  A: 

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)

jalf
Also worth noting: many compilers will let you set a warning level. If you set it high enough, it likely would have given you a warning about this. Static code analysis tools might do the same, as well.
Brian
also look into the c89 rationale for value / sign preserving promotions: http://www.lysator.liu.se/c/rat/c2.html#3-2-1-1 i read it last week and found it nice since it explains very well the rationale behind it
Johannes Schaub - litb
Compilers should give errors for invalid code. By exclusion, this implies that warnings are for valid (but dubious) code.
MSalters
+2  A: 

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.

ChrisW
A: 

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'.

MSalters