0

I have not come up with a solution for the following warning:

main.cpp: In member function 'void MyClass::increase()':
main.cpp:350: warning: conversion to 'short unsigned int' from 'int' may alter its value

main.cpp:

class MyClass {
public:
   MyClass() : myShort(0) { }
   void increase() { myShort *= 60; } // Line 350

private:
   unsigned short myShort;
};

int main(int argc, char** argv)
{
   MyClass myObj;
   myObj.increase();
}
janr
  • 3,664
  • 3
  • 24
  • 36
  • 1
    What compiler and options are you using? I tried `g++` with all warnings turned on and saw no warning with the code you're showing. – lurker Jul 27 '16 at 14:13
  • g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-17) and the g++ flag is '-Wconversion'. – janr Jul 27 '16 at 14:17
  • Thanks. I ran my test with g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 and with g++ (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2), but did not see the warning. – lurker Jul 27 '16 at 14:19
  • 1
    solution: `myShort = static_cast(myShort * 60);` .Due to integer promotion rules, casting `60` to `short` is not enough. – bolov Jul 27 '16 at 14:25
  • @bolov Thanks, the cast solves the warning. I could have vowed that I tried this, but may be I only casted the '60' like you mentioned. Why don't add it as an answer? – janr Jul 29 '16 at 14:02
  • @janr Yes the ideea is that you need split `+=` into a `=` in order to be able to do the proper cast. I can't because the question is closed :p – bolov Jul 29 '16 at 14:34

0 Answers0