tags:

views:

81

answers:

3

Interesting little bug here:

if (host != NULL) {
    printf("hi");
} else {
    printf("FAIL");
}
return 0;

doesn't print anything at all, but:

if (host != NULL) {
    printf("hi");
} else {
    printf("FAIL");
}   
fprintf(stdout, "\n%s\n", (char *)&additionalargs);
return 0;

prints

hi

abc

Does anyone know why this is?

+5  A: 

The difference is the \n characters.

As you printf characters, they are accumulated in a buffer which isn't sent to the output device until an 'end of line' character is sent.

pavium
works, thank you.
piggles
It doesn't have to be end of line. Otherwise, there'd be no way to output and receive input on a single line.
Damien_The_Unbeliever
+5  A: 

printf output to stdout is buffered. You might want to look at fflush

Damien_The_Unbeliever
I was thinking something along those lines (ie `printf` is buffered). I've only been at C for a week now.
piggles
A: 

try using fflush(stdout) before your if condition.

Manav MN
wouldn't I want that AFTER my if condition? `man fflush` says that `fflush()` forces a write on whatever output stream is given as an argument.
piggles
to get exact output, better would be place fflush both before and after if condition, otherwise previous existent data of buffer may also be printed out.
Manav MN
@Manav: it is going to be printed out anyway. `fflush()` before `if` isn't going to magically make the previous unprinted data go away!
Alok
How does adding just a '\n' in printf magically prints the buffer. I guess, (and sorry for guessing ;lol) '\n' traditionally acted like line feed and made the buffer flush before printing a new line.
Manav MN
Manav, on many systems, `stdout` is line buffered. Which means that printing a newline character flushes the buffer (or if the buffer becomes full). However, if you really want your output to be visible at certain points, you should call `fflush(stdout);` after doing any printing that doesn't involve newline.
Alok