简体   繁体   中英

Wrong format specifiers in scanf (or) printf

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?

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 integers 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-promotion 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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM