Why does scanf return random values when format not matched

Viewed 83
#include <stdio.h>

int main() {
    int i,j,k;
    scanf("%d %d %d",&i,&j,&k);
    printf("%d %d %d", i, j, k);
    return 0;
}

Upon inputting "5 .5 .5", the returned value are "5 -6229899888 32765". What is the reason behind this returned value? What is actually happening here? (Other than the first 5 of course, that was matched normally).

2 Answers

When scanf matches input text, it converts it according to the conversion specification (such as interpreting decimal for %d) and assigns the result to object pointed to by the corresponding argument.

When scanf does not make a match, it does not make an assignment.

Then the value in the corresponding object is whatever was there before scanf was called. If you have not put a value into it (by initialization or assignment), its “value” is indeterminate.1 Sometimes the value it appears to have is whatever was left in memory by earlier software that used the same memory for a different purpose.

Footnote

1 When a value is indeterminate as defined by the C standard, a compiler is not required to use its assigned memory for its value. Optimization is allowed to remove any memory loads that would have fetched its value, so the program may continue on with whatever data was in some register or another, and that can vary from place to place in the program code. This can cause an indeterminate value to appear to be different at different times.

You need to check the return value of scanf()

#include <stdio.h>

int main(void) {
    int i, j, k;
    int check = scanf("%d%d%d", &i, &j, &k);
    switch (check) {
        default: printf("error\n"); break;
        case 0: printf("no values\n"); break;
        case 1: printf("%d\n", i); break;
        case 2: printf("%d %d\n", i, j); break;
        case 3: printf("%d %d %d\n", i, j, k); break;
    }
    return 0;
}
Related