Monday, June 27, 2016

An interesting scanf() skipping behavior



It is very interesting and quite important to notice scanf() behavior in C programming,

While you are writing a code for example,

 int x; char y;  
 scanf ("%d", &x);  
 scanf ("%c", &y);  

    -- the second scanf() will not hit while you run the program. But if you reverse,

 scanf ("%c", &y);  
 scanf ("%d", &x);  

                -- it will work. But WHY ???
               
Because scanf() function reads new line character from Return key, so while something Integer has been read into a variable and then pressed Return, a New Line created due to Return key is staying in buffer and the next scanf(), which is ready to take a character variable took that New Line as character value and as it filled with a character, it automatically skip.

But on other case, as the second scanf is as integer, it does not effect with above cause.

Because, scanf() function removes whitespace automatically before trying to parse, except - again EXCEPT,

 %c, %n, %[] these three cases.