I have read this at many places, but do not understand. Why it is said that cout is more type safe than printf(). Just because it does not required to write %d %c %f
or it has some deeper meaning.
Thanks in advance.
This is why:
printf("%s\n", 42); // this will clobber the stream
This will cause a buffer overflow – the compiler cannot generally check that the format string in the first argument of printf
corresponds to the types of the subsequent arguments. It could do this in the above case – because the string is hard-coded – and some compilers do.1 But in general the format string may be determined at runtime so the compiler cannot check its correctness.
1 But these checks are special-cased to printf
. If you wrote your own myprintf
function with the same signature as printf
, there would be no way to check for type safety since the signature uses ellipsis ...
which elides all type information inside the function.
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