i'm starting to make code checking the function's return value, but i'm not sure on how to procede after I capture some errors.
For example, in fgets:
while( fgets( rta, 3, stdin ) == NULL ) {
printf( "Ocurrio un error al evaluar su respuesta. Intente nuevamente./n" );
}
But for puts ?
It will return EOF on error, so I make:
if( puts( "Message" ) == EOF ) {
error handle...
}
Question is, what I'm supossed to do if it fails. I would think in displaying a message in the console (this is a console app) but if puts fails, then my message would also fail.
(because I would also use puts).
Should I use assert to display a message and end the app?
Thanks a lot.
Unless you have some desperate need to communicate with someone/something that is no longer available, you typically ignore the return value of such functions.
If you really need a record of your progress or failure, then open a log file and write all of your messages there (or use something like syslog).
Basically, if you're using stdio, then it is likely someone at some point with either hook your program to a pipe (e.g. | less) or do some other such thing that will lead to stdout going away.
Programs like lint will complain when you ignore the return value of printf and puts, but the truth is 99% of those return values are useless except in extreme cases.
Well, as they say, If there's any doubt, there is no doubt.
It's very good of you to incorporate disciplined thinking like making sure all cases are accounted for. But if you're unsure what to do with the return value, then clearly you don't need to do anything with it.
To communicate this decision in code, you may explicitly discard the return value by casting the expression to void.
(void)puts("");
This will hush-up any warning messages about ignoring the return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With