c - What will happen if scanf() gets some character which doesn't match the format string? -


#include <stdio.h>  int main(void) {     int i, j, k;     scanf("%d%d%d", &i, &j, &k);     printf("%d %d %d", i, j, k);     return 0; } 

if input 1,2,3, happen? , why?

according https://stackoverflow.com/a/18297691/2646069 , if scanf() reads unexpected string, return not modifying value after last successful value.

i tried clang (llvm 6.1.0), on -o0, explanation above correct, on -o2, second variable random number not same before scanf(), , third variable 0.

according the manual, scanfs return value tells whether it's safe use arguments or not.

upon successful completion, these functions shall return number of matched , assigned input items; number can 0 in event of matching failure. if input ends before first matching failure or conversion, eof shall returned. if read error occurs, error indicator stream set, eof shall returned

if input 1,2,3 scanf return 1, indicating first argument safe use , match failure occured @ first , because doesn't match input expected according format string.

if make use of j or k following this, code making use of indeterminite value, undefined behaviour, source of erratic behaviour avoided... it's important check return value of scanf, link used encourages.


Popular posts from this blog