Why does scanf require% hd?

I created a very simple program with menus that take a value, and then store it in the local value of the variable and, finally, with the second option, the program prints the value.

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

thanks!

pS (I used Dev-C ++ (GCC) to compile it. It works with Visual Studio)

#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(); } 
+4
source share
9 answers

With scanf , the "h" modifier indicates that it reads a short integer whose value is your choice variable. Therefore, "% hd" only needs to be written in two bytes (on most machines) instead of the 4 bytes that "% d" writes.

For more information, see the scanf man page

+11
source

The choice variable is of type short , so you need the %h specifier in scanf to read it (in fact, you don't need d ). Type int requires %d . See Conversion Notes here

+2
source

You are reading a short text. H is necessary because% d is the default int size. See this page on the scanf page .

+1
source

It looks like your problem is that choice is short , which (usually) is 2 bytes long, and %d expects an integer that (usually) 4 bytes ... So, scanf clobbers, which comes after choice in the stack.

+1
source

choice is short , and% d indicates int .

When you specify% d, scanf should assume that the associated argument is a pointer to a memory block of size int and will write to it int . When this happens, he will most likely record data located nearby, but not in choice , and the results are undefined and probably not very good! If it works in one compiler and not in another, this is just the behavior of undefined behavior!

In GCC -Wformat, a warning should appear when you make this error.

+1
source

%d intended to be read int , not short. Your code never "worked" - it just seems that in this case you did not notice any difference between what you wanted and the undefined behavior you got.

0
source

The scanf modifier for entering a variable of type short is% hd. Therefore, you need to specify the correct modifier.

 scanf("%d",&integer); // For integer type scanf("%hd",&short_int); // For short type 

Therefore, it does not work.

0
source

Depending on the numerical addition, the final value and other similar problems, you can choose either the upper or lower part of the input value by choice; you store the rest of the input value in memory, which may or may not be used for anything else.

0
source

Source: https://habr.com/ru/post/1315822/


All Articles