Compare the codes:
const char x = 'a';
std::cout<< x;
00C31000 mov eax,dword ptr [__imp_std::cout (0C32054h)]
00C31005 push eax
00C31006 call std::operator<<<std::char_traits<char> > (0C310B0h)
00C3100B add esp,4
and
const int x = 'a';
std::cout<< x;
00271000 mov ecx,dword ptr [__imp_std::cout (272048h)]
00271006 push 61h
00271008 call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (272044h)]
and
const char* x = "a";
std::cout<< x;
00071000 mov eax,dword ptr [__imp_std::cout (72058h)]
00071005 push eax
00071006 call std::operator<<<std::char_traits<char> > (710B0h)
0007100B add esp,4
It seems that the The question – Why is there a difference in the generated code?const int version is better optimized than the const char* and the (even more surprising)const char version.
Some overloads of
operator<<(including forint, but notcharorconst char*) are members ofstd::ostream; some are non-member functions takingstd::ostream&as their first parameter.Microsoft’s compiler uses different calling conventions for member and non-member functions. I’m guessing that you’re building for 32-bit Windows. In that case member functions will use the
thiscallconvention, wherethisis passed in registerecxand the remaining arguments are passed on the stack; and non-member functions use thecdeclconvention, where all arguments are passed on the stack.