16

Simple question: Can scanf read/accept a "small integer" into an unsigned char in ANSI C?

example code un_char.c:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    unsigned char character;

    scanf("%hhu", &character);

    return EXIT_SUCCESS;
}

Compiled as:

$ gcc -Wall -ansi -pedantic -o un_char un_char.c
un_char.c: In function ‘main’:
un_char.c:8: warning: ISO C90 does not support the ‘hh’ gnu_scanf length modifier

hh isn't supported by ISO C90. So what scanf conversion can be used in this situation?

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
Tim
  • 161
  • 1
  • 3

2 Answers2

12

No: C89 (C90) does not support '%hhu' to read a string of digits into an unsigned char. That is a feature in C99.

You would have to read into an unsigned integer ('%u') or unsigned short ('%hu') and then check that the result is with the range of an unsigned char.

Yamaneko
  • 3,433
  • 2
  • 38
  • 57
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
3

Read it into an unsigned short/int and do some range checking after if you need to.

nos
  • 223,662
  • 58
  • 417
  • 506
  • Unsigned short would be the better datatype as that's 16 bits...just knock off the upper 8 bits.. :) – t0mm13b Feb 09 '10 at 17:39
  • 1
    @tommieb75: There's no guarantee that `unsigned short` is 16 bits. There's no guarantee that `unsigned char` is 8 bits either. – jamesdlin Feb 09 '10 at 20:59
  • @jamesdlin: I agree...due to the different processors/compilers/linkers/runtime environments... :O :) – t0mm13b Feb 09 '10 at 21:12
  • @jamesdlin: I believe there is a guarantee that a char is at least 8 bits, which is enough – Matt Joiner Jun 19 '10 at 15:06
  • @Matt Joiner: Yes, but my point was that you can't just knock off the upper 8 bits (as tommieb76 suggested) and that you should do range-checking (as nos suggested). – jamesdlin Jun 19 '10 at 15:41