user2256825 user2256825 - 1 year ago 179
C++ Question

overflow in implicit constant conversion warning while assigning string size(string::npos) to an integer variable

How to get rid of the the warning below?

size_t filesize = getFilesize(strLogFileName.c_str());
// Open file
int fd = open(strLogFileName.c_str(), O_RDONLY, 0);
assert(fd != -1);
// Execute mmap
char* mmappedData =
(char *) mmap(NULL, filesize, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
assert(mmappedData != NULL);
string strFileContent(mmappedData);

// warning: overflow in implicit constant conversion
int pos, lpos = string::npos;

What changes could be required in the code to fix this warning, rather than ignoring this warning?

Answer Source

string::npos is of type size_t. Assigning a size_t to an int can cause an overflow during conversion. Fix it as follows:

size_t pos;
size_t lpos = string::npos;

Or, as suggested by user2079303 you can use either string::size_type or, more conveniently, auto if you want to support strings with custom allocators.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download