Sunday, September 9, 2012

Wrong Input Through scanf, What Happens?

scanf does not assign the value entered in case of wrong input.

Go through the following lines of code:

#include<stdio.h>
#include<conio.h>

void main(){
int x=100;
scanf("%d", &x);
printf("Value of x is = %d", x);
getch();
}

Now the scanf is supposed to scan an integer value. Take 2 cases where you input:
(i) 2
(ii) d (or any character)

In (i) printf prints Value of x is = 2.
In (ii) printf prints Value of x is = 100.

Note that when you give wrong input to scanf, it does not assign any value to x and so the previous value of x is retained.

PS1: Compiler used TurboC.
PS2: Corrections/Suggestions/Comments are welcome!

No comments:

Post a Comment