6
Looking at the documentation of scanf()
I saw that it returns a value, but I see the codes using it without using that return. This is right?
6
Looking at the documentation of scanf()
I saw that it returns a value, but I see the codes using it without using that return. This is right?
7
In fact it is wrong. But the use of scanf()
is usually wrong at other points, even the use of it is already a mistake. It happens that in general the staff is only doing an exercise and it does not matter, but if the person wants to do right should check the return that is a code error.
Just because people tend to ignore it they’re afraid of error codes. Of course the programmer can make mistakes much more serious than ignoring the error code and that people just consider that the programmer has to do it right. Here it is worth the same. If he ignores the code is his problem. I admit that ideally it would be the case to return something that cannot be used directly without checking if it is ok, but this is not the philosophy of C.
The problem occurs with several functions. An example is the malloc()
. If he returns one NULL
you can’t use that, but in exercises it’s common for the person not to check if the allocation went well, which will be a tragedy if it goes wrong.
This goes for numerous C functions.
The right thing would be something like this:
#include <stdlib.h>
#include <stdio.h>
int main(void) {
char *texto = malloc(10);
if (texto == NULL) {
printf("Houve um erro de alocação de memória");
exit(EXIT_FAILURE);
}
int x;
if (scanf("%d", &x) != 1) {
printf("Houve um erro de leitura do dado");
free(texto);
exit(EXIT_FAILURE);
}
printf("%d", texto);
free(texto);
return EXIT_SUCCESS;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference. Note that it is to give error even.
Browser other questions tagged c c++ function return
You are not signed in. Login or sign up in order to post.