locked
C4838: conversion from 'int' to 'std::size_t' requires a narrowing conversion--why? RRS feed

  • Question

  • The following gets a compiler warning C4838: conversion from 'int' to 'std::size_t' requires a narrowing conversion.

    size_t firstNonZero[2] = { -1, -1 };
    but if I explicitly cast the values to size_t, the error goes away.
        size_t firstNonZero[2] = { static_cast<size_t>(-1), static_cast<size_t>(-1) };
    Why is a narrowing conversion required? In other words, why is -1 not coercible to size_t without any possible data loss?


    Friday, March 3, 2017 9:26 PM

Answers

  • In Visual Studio, when I hover the mouse over size_t it tells me it is a typedef of unsigned int or unsigned long long depending on target platform.

    Also, of course, the explicit cast will make it go away because doing that will set it to UINT32_MAX or UINT64_MAX. That is obviously not something you want because a number that is larger than 4 billion or 18 quadrillion (or whatever) is a little bit larger than -1 right?


    This is a signature Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Friday, March 3, 2017 9:41 PM

All replies

  • In Visual Studio, when I hover the mouse over size_t it tells me it is a typedef of unsigned int or unsigned long long depending on target platform.

    Also, of course, the explicit cast will make it go away because doing that will set it to UINT32_MAX or UINT64_MAX. That is obviously not something you want because a number that is larger than 4 billion or 18 quadrillion (or whatever) is a little bit larger than -1 right?


    This is a signature Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because the major point of my posts is to aid in the learning process.

    Friday, March 3, 2017 9:41 PM
  • Thanks for the quick explanation; of course you are right. For some reason, I was thinking that size_t was signed.
    Friday, March 3, 2017 9:55 PM