Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is %hd necessary in scanf?

Tags:

c

I created a very simple progam whith a menu, that take a value, then memorize it into the local variable value, and finally with the second option the progam prints the value.

my question is: Why does the program work only if I add an "h" to the scanf parameter? In other words: what kind of relation there is between scanf() and my local int value variable?

thanks!

p.S. (I used Dev-C++ (GCC) to compile it. With Visual Studio it works)

#include <stdio.h>

main () {

    int value = 0;
    short choice = 0;

    do {
       printf("\nYour Choice ---> ");
       scanf("%d", &choice);  /* replace with "%hd" and it works */

       switch (choice) {
          case 1:
               printf("\nEnter a volue to store ");
               scanf("%d", &value);
               getchar();              
               printf("\nValue: %d", value);
               break;
          case 2:
               printf("\nValue: %d", value);            
               break;  
       }

    } while (choice < 3);

    getchar();
}
like image 978
Mario Avatar asked Jul 15 '10 16:07

Mario


2 Answers

With scanf, the "h" modifier indicates that it's reading a short integer, which your variable choice just happens to be. So the "%hd" is necessary to write only two bytes (on most machines) instead of the 4 bytes that "%d" writes.

For more info, see this reference page on scanf

like image 159
Randolpho Avatar answered Sep 19 '22 11:09

Randolpho


The variable choice is of type short so that's why you need the %h specifier in scanf to read into it (in fact you don't need the d here). The int type just requires %d. See the notes on conversions here

like image 45
bjg Avatar answered Sep 21 '22 11:09

bjg