Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does printf fail to print?

Tags:

c

printf

printf function in c doesn't always print the output on screen. For example if you forget to put \n at the end of string you are printfing you sometimes don't get the o/p. Are there some other conditions when printf doesn't print. I remember someone saying that there are 7 such conditions. Can you guys please help.

like image 207
disputedbug Avatar asked Feb 16 '12 19:02

disputedbug


2 Answers

Standard out is a buffered stream, it is not guaranteed to flush unless a newline is put in, the stream is closed, or the program exits normally. If the program exits abnormally, it is possible for the stream to not flush. Standard out is line buffered, which is why a newline will flush it. There are buffers that will not flush with a newline.

like image 62
user1214634 Avatar answered Nov 09 '22 09:11

user1214634


its not that printf won't always print, its that it isn't guaranteed to print immediately. This means that if you are using it for debugging purposes, then you can't guarantee that it will happen exactly when it does in the code. If you want to make sure that it does print exactly when you said it call fflush(stdout).

Note: You typically don't want to use fflush(stdout) unless you are debugging, its really resource intensive and if you care about speed performance at all it has the potential to slow you down.

like image 43
Irony Avatar answered Nov 09 '22 10:11

Irony