6 ms·
So, why does puts do "return r ? EOF : '\n';"? Some backwards compatibility? Or is there a logical reason for that?
by mormegil 5y ago
So, why does puts do "return r ? EOF : '\n';"? Some backwards compatibility? Or is there a logical reason for that?
- masklinn 5y agoPer the man: > puts() and fputs() return a nonnegative number on success, or EOF on error. r is the result of the write, if it’s nonzero the write failed and thus so did puts.
- m45t3r 5y agoYeah, but I think the question was why EOF and "\n". It could as easily just return 1 or -1 for example, and it would make more sense I think.
- kevin_thibedeau 5y agoputs() always adds a line termination so success means that '\n' is the last char for that implementation.
- masklinn 5y agoThat's more of an implementation detail, probably a BC remnant from when it called putchar in a loop and you’d get the result if the last putchar.
- _kst_ 5y agoThat particular implementation probably returns the result of the last fputc() or equivalent that it called. puts() returns EOF (typically -1) on error, or some unspecified non-negative value on success. fputc() returns EOF on error or the written character, treated as an unsigned char and converted to int, on success. Don't expect all puts() implementations to do the same thing. For example, the glibc implementation appears to return the number of characters written on success. Implementations are free to rely on implementation-defined behavior. User code that's intended to be portable cannot.
- LukeShu 5y agoThat particular implementation (NetBSD's) (which is transcribed in to the article) does something more optimized than making repeated calls to `putchar()`. But as pdw's link shows, what you suggest is exactly what the historical implementation was. So NetBSD is simply matching historical Unix.
- nwellnhof 5y agoFor what it's worth, musl's implementation returns 0 on success.
- pdw 5y agoIt's what historic Unix did: https://github.com/v7unix/v7unix/blob/master/v7/usr/src/libc/stdio/puts.c https://github.com/v7unix/v7unix/blob/master/v7/usr/src/libc... Why it did that? I'm not sure, but at the time C did not have 'void' functions: every function returned a value. They probably wanted to make the behavior of the stdlib functions deterministic, even if the return value was useless and undocumented.