N
is uninitialised meaning N
could have any integer value. That unknown value is copied to M
, and then scanf()
called to assign a value to N
.
The program needs to verify that system calls (like scanf()
) has done what was expected with user input.
Below is a “better” version that tries to protect itself to an extent.
int main() { // it's okay to use whitespace to enhance readability.
int N, M;
if( scanf( "%d", &N ) != 1 )
printf( "scanf didn't assign a value!\n" );
M = N;
printf( "%d\n", M );
getchar();
return 0;
}
Notice what happens when a user does something unexpected. This is the output
fifteen
scanf didn't assign a value!
22
ALWAYS validate user input before using it.
5
solved Why am I getting an output of always 1 in the below code