What does the # sign after the% sign in scanf () mean?

What does the following code mean in C

scanf("%d%#d%d",&a,&b,&c); 

if the given values โ€‹โ€‹are 1 2 3 , it gives the result as 1 0 0

PS- I know that it is used with the printf() operator, but here, in the scanf() expression, it gives random behavior.

+6
source share
2 answers

TL DR; - A # after the % sign in the format string of the scanf() function is the wrong code.

Explanation:

# is the flag symbol that is allowed in fprintf() and in the family, not in fscanf() and in the family.

In the case of your code, the presence of # after % considered as an invalid conversion specifier. According to 7.21.6.2,

If conversion specification is invalid, undefined behavior

So your code produces undefined behavior .

Hint: you can check the return scanf() value to check how many items have been "scanned" successfully.


However, FWIW, using # with %d in printf() , is also an undefined behavior .

For reference only: in accordance with standard document C11 , chapter ยง7.21.6.1, part of the flag symbols, (highlighted by me)

#

The result is converted to an alternative form. To convert o it increases accuracy, if and only if necessary, to make the first digit of the result be zero (if the value and accuracy are both 0 , one 0 is printed). For the conversion of x (or x ), 0x (or 0x ) has a great result, a prefix to it. For conversions a , a , e , e , f , f , g and g result of converting a floating point number always contains a decimal character, even if it is not followed by digits. (Usually, the decimal point symbol appears as a result of these transformations only if a digit follows it.) For transformations g and g trailing zeros are not removed from the result. For other conversions, the behavior is undefined.

+12
source

According to the Standard, the use of # is illegal.

Using it causes your program to call Undefined Behavior .

Of course, if your implementation defines it, it is determined by the behavior for your implementation , and it does what your documentation says .. p>

+3
source

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


All Articles