I have recently switched to VC++ 2005 express edition, and noticed warnings in my projects which weren't there before. I'm not an expert, so I was wondering if the compiler is right in warning me about a conversion in this code:
void main()
{
short a = 4;
short b = 2;
b += a;
}
test.cpp(5) : warning C4244: '+=' : conversion from 'int' to 'short', possible loss of data
Where did the 'int' come into existence "b = b + a" doesn't give any problems - isn't that supposed to be exactly the same

+= and conversions
vikram123
I copied your code and did not get the error. Maybe you changed a setting somewhere.
I mean I did not get a warning.
Ing. Andreas Pollak
Check this: http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=171059&SiteID=1
Cheatah
Just for your reference;
#include <iostream>
using namespace std;
int main()
{
short a = 4;
short b = 2;
// b += a;
short int c = short int (a + b);
cout << c << endl;
}
Dr.Stroustrup repeats at varous places that "Type" is very important in C++. I always follow his advice. If someone else has a different opinio, plz let us know it.
Dudde
The only thing I'm really concerned about is the speed of the code. I was under the impression x += y could be faster than x = x + y, in cases where 'x' has to be evaluated such as array[a * 2 + b] += y. Manually creating a temporary variable would be a bit ugly, and evaluating x twice is not an option obviously. On the other hand conversions are also slow. Perhaps I'd better overload these operators and do some speed tests.
Ahren
Set " Treat Warning As Error" switch ON when you build it.
Hemant Sathe
I'd better overload these operators and do some speed tests.
I hope you will get a good result.
DNA123
Takashi, I've compiled your code with Treat Warning as Error" and it compiles and runs (if I uncomment 'b += a;', it gives the warning/error again, of course). Here's the (expected) output:
2
2
2
2
4
4
11
The compiler also gives a warning for 'short int' (ie, 'sa += sb' will also result in a conversion).
I forgot to mention, this warning is only there with warning set to Level 4. I created a default Win32 console project, and I don't remember changing much in VC's options (apart from some directories and such of course).
ECS
Try this.
#include <iostream>
using namespace std;
int main()
{
short a = 4;
short b = 2;
short int sa = 4;
short int sb = 2;
int c = 5;
int d = 6;
// b += a;
c += d;
cout << sizeof(a) << endl << sizeof(b) << endl;
cout << sizeof(sa) << endl << sizeof(sb) << endl;
cout << sizeof(c) << endl << sizeof(d) << endl;
cout << c << endl;
}
Hope this helps.
redcamel
Thank you very much for the info. It's really interesting. I wil keep every logic as simple as possible so that the compiler understands my intention.
Best,