Wrong format specifiers in scanf (or) printf

2019-01-05 05:36发布

As of the printf function is concerned, I understand the following from few references and experiments.

  • When we try to print an integer value with format specifiers that are used for float (or) double and vice the versa the behaviour is unpredictable.
  • But it is possible to use %c to print the character equivalent of the integer value. Also using of %d to print ASCII value (integer representations) of character is acceptable.

Similarly, what is the behaviour of scanf, if there is a mismatch of format specifier and the arguements passed to scanf. Does the standards define it?

1条回答
甜甜的少女心
2楼-- · 2019-01-05 05:59

Variadic arguments (those matching the ellipsis, ...) are default-promoted. That means that all shorter integral types are promoted to int (or unsigned, as appropriate). There's no difference between inte­gers and characters (I believe). The difference between %d and %c in printf is merely how the value is formatted.

scanf is a different kettle of fish. All the arguments you pass are pointers. There's no default-pro­mo­tion among pointers, and it is crucial that you pass the exact format specifier that matches the type of the pointee.

In either case, if your format specifier doesn't match the supplied argument (e.g. passing an int * to a %p in printf), the result is undefined behaviour, which is far worse than being "unpredictable" -- it means your program is simply ill-formed.

查看更多
登录 后发表回答