2

I have a program that uses unsigned chars to represent integers with a small range. I find myself needing to clear them to 0 in several different parts of the program, I have also recently started using splint and apparently:

unsigned char c = 0;

gives the warning:

Variable c initialized to type int, expects unsigned char: 0
  Types are incompatible.

As there is no suffix for a literal char, How is it best to resolve this? I think I have a few options:

1: Ignore the warning.

2: Cast every time:

unsigned char c = (unsigned char)0;

3: Make a var to cut down the length of the code:

unsigned char uc_0 = (unsigned char)0; 
unsigned char c = uc_0;

4: A function:

static inline unsigned char uchar(int in)
{
   return (unsigned char)in;
}
unsigned char c = uchar(0);
jayjay
  • 1,017
  • 1
  • 11
  • 23
  • IMO, you should go for option 4. and no need of casting there in `return` statement, as we know, `If the expression has a type different from the return type of the function in which it appears, the value is converted as if by assignment to an object having the return type of the function.` from chapter `6.8.6.4`, `c99`. – Sourav Ghosh Jan 12 '15 at 14:11
  • @iharob not a compiler, Splint: http://www.splint.org/ – jayjay Jan 12 '15 at 14:12
  • @SouravGhosh Thanks, that makes a lot of sense, however I do need the cast for warning free output from splint: `Return value type int does not match declared type unsigned char` – jayjay Jan 12 '15 at 14:13
  • 1
    This warning seems to be safe to ignore. I would not consider this kind of assignment to be wrong or dubious. – fuz Jan 12 '15 at 14:20

2 Answers2

2

splint has an option +charint that will treat char int as interchangeable.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

You can ignore the warnings and use

unsigned char = 0;

In many cases when there is integer operation in order to save memory instead of using int which obviously consumes extra memory than char people do make use of unsigned char.

unsigned char i = 10;
unsigned char j = 1;
unsigned char k = i +j;
printf("%d",k);
Gopi
  • 19,784
  • 4
  • 24
  • 36