Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How cout is more typesafe than printf()

Tags:

c++

c

cout

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.

like image 847
Pranit Kothari Avatar asked Jul 22 '13 13:07

Pranit Kothari


Video Answer


1 Answers

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.

like image 83
Konrad Rudolph Avatar answered Sep 28 '22 01:09

Konrad Rudolph