tags:

views:

49

answers:

2

the following code:

signed char sc = ~0xFC;
unsigned char uc = ~0xFC;

when compiled gives me the following warnings:

integer conversion resulted in truncation
integer conversion resulted in truncation
  1. why do i get these warnings
  2. how do i write my code, so that i dont get these warnings (without using #pragmas)

thanx,

i'm using IAR Compiler for 8051,

do you get similar warnings when compiling using other compilers?

+2  A: 

In C, arithmetics are performed at least at the size of int. That means, ~0xFC will return an int. Even more, this value is 0xFF03 which is way beyond the range of char (signed or not).

Therefore, the assignment will give the two warnings. You could try

signed char sc = ~0xFC & 0xFF;

to see if the compiler knows that the result is within the range of char (gcc won't complain after adding the & 0xFF). You could also try to add an explicit cast:

signed char sc = (signed char)~0xFC;
// also possible:
// signed char sc = ~(signed char)0xFC;

or, as the value can be easily computed, why not just

signed char sc = 3;
KennyTM
ITYM `0xFFFFFF03` (@ 32 bits), and `3` in the last line.
Paul R
@Paul: I'm not sure if the `int` is 32-bit, as 8051 is a 16-bit architecture, according to Wikipedia.
KennyTM
@KennyTM, your answer is not correct in the sense that the `~` may well be applied to any integer type, in particular to `char` and then it returns a `char`. The unfortunate thing is that there is no such thing like a character constant literal in C, even the `'\0xx'` notation is `int`. So you'd have to do it as Jack proposes in his answer to obtain a character constant and then everything works fine.
Jens Gustedt
@KennyTM: indeed - it was the 03 rather than 04 that I was pointing out, but I see you've fixed that now.
Paul R
+6  A: 

Because hexadecimal literals are considered int when written like you did 0xFC.. to avoid the warning just cast them to truncate the number to just 1 byte:

~((char) 0xFC)

0xFC is considered 0x000000FC on a 32 bit architecture, so when you apply not you obtain 0xFFFFFF03, this means that when you assign this result to a char the 3 most relevant bytes are just discarded and the compiler warns you about it.

Jack