John Paul Coder
John Paul Coder

Reputation: 313

Warning C4267 'initializing': conversion from 'size_t' to 'DWORD', possible loss of data

I am getting the below warning message when compiling my C++ application,

Warning C4267 'initializing': conversion from 'size_t' to 'DWORD', possible loss of data at the below line:

DWORD nPos = strRegPath.find(REG_SOFTWARE); 

Below is my complete code:

Declaration:

#define REG_SOFTWARE L"Software"
wchar_t* m_wszParams;

Definition:

wstring strRegPath = m_wszParams;

DWORD nPos = strRegPath.find(REG_SOFTWARE); 

Could anyone please help me how to resolve this warning?

Thanks in advance.

Upvotes: 1

Views: 1528

Answers (1)

Bathsheba
Bathsheba

Reputation: 234715

The problem is caused by DWORD falling behind std::size_t in terms of size. If writing

std::size_t nPos = strRegPath.find(REG_SOFTWARE); 

merely kicks the can down the road, that is you get a warning elsewhere, then you can either force the issue with

static_cast<DWORD>(strRegPath.find(REG_SOFTWARE));

whereupon you're essentially telling the compiler you know what you're doing which ought to be sufficient to suppress the warning, or use something that makes a run-time check to verify you're not losing data: a numeric_cast from Boost can help there:

https://www.boost.org/doc/libs/1_38_0/libs/numeric/conversion/doc/html/boost_numericconversion/improved_numeric_cast__.html

Upvotes: 2

Related Questions