Preventing warning "Possible loss of data"?

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Preventing warning "Possible loss of data"?

5,113 Views
BasePointer
Contributor II
Hi,
 
I'm new at CW and using MS9S08LC60. The compiler gives me "Possible loss of data" warning at the line below. How can I prevent the compiler to give this warning?
 
 
void ByteToBcd(char val, char* bcd)

 char tmp = val % 100; <- Warning C2705: Possible loss of data
 *bcd++ = (tmp / 10) + '0';
 *bcd = (tmp % 10) + '0'; 
}
 
Thank you.
Labels (1)
Tags (1)
0 Kudos
4 Replies

873 Views
Lundin
Senior Contributor IV
That one is annoying, yeah... Codewarrior is one of the most paranoid compilers out there.

Put #pragma MESSAGE DISABLE C2705 in a global h-file to get the compiler to shut up when you write perfectly fine ANSI C. If the compiler was smart, it would know that the result of "TypeX / TypeY" can't be larger than sizeof(TypeX) bytes and therefore fit into the TypeX variable you store the result inside.

873 Views
StephenRussell
Contributor I
Try:
 
char tmp = ( char )( val % 100 ) ;
 
C does all integer arithmetic as int or long, as required by the largest operand. 
 
This means that the expression val % 100 is type int.  The compiler is warning you that for some values of val the result may not fit in a char. 
 
Adding the cast to char tells the compiler you do, in fact, want to throw away any high order bits that get lost in converting int to char.
 
 
 
0 Kudos

873 Views
BasePointer
Contributor II
Interesting but, type casting worked. If so, I don't understand why the compiler doesn't generate same warning for other lines:
*bcd++ = (tmp / 10) + '0';
*bcd = (tmp % 10) + '0';
 
If the right side of the equations are type int, shouldn't the compiler generate same warning?
 
Regards.
0 Kudos

873 Views
bigmac
Specialist III
Hello,


BasePointer wrote:
Interesting but, type casting worked. If so, I don't understand why the compiler doesn't generate same warning for other lines:
*bcd++ = (tmp / 10) + '0';
*bcd = (tmp % 10) + '0';
 
If the right side of the equations are type int, shouldn't the compiler generate same warning?

It would appear that the addition of the character constant makes the intent clear to the compiler - remove the addition process and the C2705 warning will (re)appear.

Another possible issue for the first line may be -
Does the assignment of the value to the pointer location occur before or after the pointer is incremented?
I seem to recall having read that this cannot be guaranteed for pointers - but perhaps may not be correct.  Others may be able to advise whether there is really an ambiguity or compiler dependency in this respect.  I have usually thought it prudent to increment the pointer as a separate operation.

Regards,
Mac