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.
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 both0
, a single0
is printed). Forx
(orX
) conversion, a nonzero result has0x
(or0X
) prefixed to it. Fora
,A
,e
,E
,f
,F
,g
, andG
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.) Forg
andG
conversions, trailing zeros are not removed from the result. For other conversions, the behavior is undefined.
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.
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