Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What does the following code mean,in C

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

if given values 1 2 3 it gives output as 1 0 0

P.S- I know it is used with printf() statement but here in scanf() statement it gives random behaviour.

like image 825
FossArduino Avatar asked Apr 27 '15 09:04

FossArduino


2 Answers

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

Explanation:

The # here is a flag character, which is allowed in fprintf() and family, not in fscanf() and family.

In case of your code, the presence of # after % is treated as invalid conversion specifier. As per 7.21.6.2,

If a conversion specification is invalid, the behavior is undefined

So, your code produces undefined behaviour.

Hint: you can check the return value of scanf() to check how many elements were "scanned" successfully.


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

Just for reference: As per the C11 standard document , chapter §7.21.6.1, flag characters part, (emphasis mine)

#

The result is converted to an ‘‘alternative form’’. For o conversion, it increases the precision, if and only if necessary, to force the first digit of the result to be a zero (if the value and precision are both 0, a single 0 is printed). For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversions, the result of converting a floating-point number always contains a decimal-point character, even if no digits follow it. (Normally, a decimal-point character appears in the result of these conversions only if a digit follows it.) For g and G conversions, trailing zeros are not removed from the result. For other conversions, the behavior is undefined.

like image 91
Sourav Ghosh Avatar answered Nov 11 '22 20:11

Sourav Ghosh


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

Its use makes your program invoke Undefined Behaviour.

Of course, if your implementation defines it, it is defined behaviour for your implementation and it does what your documentation says.

like image 36
pmg Avatar answered Nov 11 '22 22:11

pmg