What will be the output of the following program:
main( )
{
int i ;
printf ( "Enter value of i " ) ;
scanf ( "%d", &i ) ;
if ( i = 5 )
printf ( "You entered 5" ) ;
else
printf ( "You entered something other than 5" ) ;
}
{
int i ;
printf ( "Enter value of i " ) ;
scanf ( "%d", &i ) ;
if ( i = 5 )
printf ( "You entered 5" ) ;
else
printf ( "You entered something other than 5" ) ;
}
And here is the output of two runs of this program...
Enter value of i 200
You entered 5
Enter value of i 9999
You entered 5
Surprising? You have entered 200 and 9999, and still you find in either case the output is ‘You entered 5’. This is because we have written the condition wrongly. We have used the assignment operator = instead of the relational operator ==. As a result, the condition gets reduced to if ( 5 ), irrespective of what you supply as the value of i. And remember that in C ‘truth’ is always non-zero, whereas ‘falsity’ is always zero. Therefore, if ( 5 ) always evaluates to true and hence the result.
Another common mistake while using the if statement is to write a semicolon (;) after the condition, as shown below:
main( )
{
int i ;
printf ( "Enter value of i " ) ;
scanf ( "%d", &i ) ;
if ( i == 5 ) ;
printf ( "You entered 5" ) ;
}
printf ( "You entered 5" ) ;
}
The ; makes the compiler to interpret the statement as if you have written it in following manner:
if ( i == 5 )
;
printf ( "You entered 5" ) ;
Here, if the condition evaluates to true the ; (null statement, which does nothing on execution) gets executed, following which the printf( ) gets executed. If the condition fails then straightaway the printf( ) gets executed. Thus, irrespective of whether the condition evaluates to true or false the printf( ) is bound to get executed. Remember that the compiler would not point out this as an error, since as far as the syntax is concerned nothing has gone wrong, but the logic has certainly gone awry. Moral is, beware of such pitfalls.
The following figure summarizes the working of all the three logical operators.
No comments:
Post a Comment