user2256825 user2256825 - 8 months ago 98
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?


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.