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();
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With