4 ms·
"\n" is a linebreak which would guarantee the text is printed and place whatever output came afterwards on the next line.
by Lukeas14 15y ago
"\n" is a linebreak which would guarantee the text is printed and place whatever output came afterwards on the next line.
- derefr 15y agoIsn't the output stream at least guaranteed to be flushed once on completion of the program, though?
- djcapelis 15y agoYes, it flushes completely outputting all characters. None of which contain a newline. Flushing doesn't automatically add newlines for you in C. It flushes the buffers you gave it, it doesn't make new stuff up to print out along with your buffers.
- derefr 15y ago(Right, I didn't mean to suggest it added a newline; just that adding a newline flushes the buffer, which was one half of the problem with missing a newline—but that if this is the only line of the program, this half of the problem is obviated.)
- getsat 15y agoAdding a newline doesn't flush anything. You'd want to call fflush() to do that.
- bremac 15y agoprintf prints to standard output, which is line-buffered by default when reading from a tty on UNIX variants. This can lead to strange problems for those who try to use it to track which parts of a program are being executed, as demonstrated by the following program with an infinite loop: #include <stdio.h> int main(int c, char **v) { printf("Hello\nJello"); while(1) ; return 0; }
- getsat 15y agoYes. You're not agreeing or disagreeing with me. Did you reply to the wrong post? Also, using printf() for debugging? In 2011? I seriously hope you guys don't do this.
- bremac 15y agoAdding a newline into a line buffer (which is a user-space buffer) flushes the buffered data up to and including the newline. fflush also flushes a user space buffer. Also, the "for those" implies I'm talking about someone else, not myself.
- jimbokun 15y ago"Also, using printf() for debugging? In 2011? I seriously hope you guys don't do this." OK, I'll bite. I haven't done any serious straight up C programming in over a decade, and yes, I used a lot of printf for debugging back then. What's the best way to debug C programs now? (I imagine printf wasn't the best way to debug programs when I was writing C, either.) A different logging library? gdb?
- getsat 15y agoprintf() is fine if you just want to see if something is being run (assuming, of course, you recognize the flushing caveat we're discussing). If you're dumping printf()s all over the place to see exactly what flow your program is taking at runtime, you're better off just setting a breakpoint or two and using a debugger to quickly step through it.