Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / Managed C++ / May 2005

Tip: Looking for answers? Try searching our database.

Weird conversion warning

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Josué Andrade Gomes - 25 May 2005 15:36 GMT
Take this code:
1: int main()
2: {
3:   unsigned short x[5] = { 1, 2, 3, 4, 5 };
4:   unsigned short sum = 0;
5:
6:   for (int i = 0; i < 5; ++i) {
7:     sum += x[i];
8:   }
9: }

CL version 13.10.3077 gives the following warning:

err.cpp(7) : warning C4244: '+=' : conversion from 'int' to 'unsigned
short', possible loss of data

Is this correct? Which possible loss of data the compiler is seeing here?
Tamas Demjen - 26 May 2005 01:46 GMT
> Take this code:
>  1: int main()
[quoted text clipped - 13 lines]
>
> Is this correct? Which possible loss of data the compiler is seeing here?

C++ compilers implicitly convert your unsigned short type into int for
the addition operation ('+='). Generally speaking it's not a good idea
to use types such as unsigned short, unless there's a tremendous amount
of data, and you want to save memory and fetch time. However, for simple
variables such as 'sum' and 'i' you should use int. The processor is not
able to work with 16-bit or 8-bit numbers efficiently, the ALU can only
work with 32-bit numbers. Every time you use an unsigned short, you have
to know that the compiler will translate it into int every time you do
anything (except assignment) to them.

The warning is there because your code is compiled to something like this:

for(int i = 0; i < 5; ++i)
{
   int temp_x = x[i];
   int temp_sum = sum;
   temp_sum += temp_x;
   sum = temp_sum; // possible loss of data here
}

This is much less efficient than if you declared sum int or unsigned.

Tom

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.