Home > database >  Why am I getting an output of always 1 in the below code
Why am I getting an output of always 1 in the below code

Time:09-17

I was writting a program to assign the Value of N to M in the declaration statement.If i gave value of N in declaration i get the same value in output.But if i read from user ,i am getting 1 always

#include<stdio.h>
#include<conio.h>
main()
{ clrscr();
 int N,M=N;    
 scanf("%d",&N); 
 printf("%d",M);  
 getchar();
 return 0;
}
     

CodePudding user response:

When you declare the value of N to M, N does not have any value, that is why you are always getting one. You need to assign the value after getting it from the user.

#include<stdio.h>
#include<conio.h>
main()
{ clrscr();
 int N,M;    
 scanf("%d",&N);
 M=N; 
 printf("%d",M);  
 getchar();
 return 0;
}

CodePudding user response:

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.

  • Related