user2256825 user2256825 - 2 months ago 44x
C++ Question

How to resolve the warning: overflow in implicit constant conversion

Though i checked the post with talks about this warning, there is no solution on how to tackle this and correct the code

Below is the line of code , that gives this warning

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

And here is the code:

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);
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.