Share
 
 

Strategies for Fixing Expansion and Truncation Errors

Here are some strategies for handling type expansion and truncation errors.

  • Use a pointer-sized (64-bit) variable to avoid expansion or truncation during assignment
  • When you are sure it is safe to do so, use a hard cast to truncate a 64-bit value, such as size_t, to 32 bits, as shown below:
    std::vector<int> myVec;
    long nVecSize = (long)myVec.size(); // no warning
  • When you are sure it is safe to do so, replace a 64-bit incoming value with a 32-bit value, as shown below:
    extern long myGetSize(const std::vector<int> & ); // applies the truncation hard cast internally
    std::vector<int> myVec;
    long nVecSize = myGetSize(myVec );
  • Temporarily disable the compiler warning and then re-enable it, as shown below:
    std::vector<int> myVec;
    // we know size is < 4G, so is okay to ignore warning
    #pragma warning (push)
    #pragma warning (disable: 4267)
    long nVecSize = myGetSize(myVec);
    #pragma warning (pop)

Was this information helpful?