Should we neglect the return of functions in C that already receive the desired value by the parameter by reference?

5

Looking at the documentation from scanf() I saw it return a value, but I see the codes using her without making use of this return. Is this right?

    
asked by anonymous 13.03.2017 / 14:35

1 answer

6

In fact, it is wrong. But using scanf() is often wrong on other points, even using 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 the right thing should check the return that is a code error.

Just because people usually ignore this people are afraid of error codes . Of course the programmer can make much more serious mistakes than ignoring the error code and that people just consider that the programmer has to do it right. Here's the same. If he ignores the code that is his problem. I admit that ideally would be the case of returning something that can not 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 malloc() . If it returns a NULL it can not use that, but in exercises it is common for the person not to check if the allocation worked, which will be a tragedy if it goes wrong.

This holds true for many C functions.

The most correct would look 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;
}

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

    
13.03.2017 / 14:35