What is the format specifier for unsigned short int?

CScanf

C Problem Overview


I have the following program

#include <stdio.h>

int main(void)
{
    unsigned short int length = 10; 
            
    printf("Enter length : ");
    scanf("%u", &length);

    printf("value is %u \n", length);

    return 0;
}

Which when compiled using gcc filename.c issued the following warning (in the scanf() line).

warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 2 has type ‘short unsigned int *’ [-Wformat]

I then referred the C99 specification - 7.19.6 Formatted input/output functions and couldn't understand the correct format specifier when using the length modifiers (like short, long, etc) with unsigned for int data type.

Is %u the correct specifier unsigned short int? If so why am I getting the above mentioned warning?!

EDIT: Most of the time, I was trying %uh and it was still giving the warning.

C Solutions


Solution 1 - C

Try using the "%h" modifier:

scanf("%hu", &length);
        ^

> ISO/IEC 9899:201x - 7.21.6.1-7 > > Specifies that a following d , i , o , u , x , X , or n conversion > specifier applies to an argument with type pointer to short or > unsigned short.

Solution 2 - C

For scanf, you need to use %hu since you're passing a pointer to an unsigned short. For printf, it's impossible to pass an unsigned short due to default promotions (it will be promoted to int or unsigned int depending on whether int has at least as many value bits as unsigned short or not) so %d or %u is fine. You're free to use %hu if you prefer, though.

Solution 3 - C

From the Linux manual page:

h      A  following  integer conversion corresponds to a short int or unsigned short int argument, or a fol‐
lowing n conversion corresponds to a pointer to a short int argument.

So to print an unsigned short integer, the format string should be "%hu".

Solution 4 - C

Here is a good table for printf specifiers. So it should be %hu for unsigned short int.

And link to Wikipedia "C data types" too.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSangeeth SaravanarajView Question on Stackoverflow
Solution 1 - CcnicutarView Answer on Stackoverflow
Solution 2 - CR.. GitHub STOP HELPING ICEView Answer on Stackoverflow
Solution 3 - CSome programmer dudeView Answer on Stackoverflow
Solution 4 - CFooBar167View Answer on Stackoverflow