3 common mistakes in if statement

From my experience I have seen student’s making these three common mistakes in if statement. So, I decided to tell you about these mistakes so you don’t repeat them. Hope this will be beneficial to you.

Mistake no. 1

Look at the program given below

int main() 
char c = 'a'; 
if ( c == 'b' ); 
printf("%c", c); 
Now guess the output of the above program?
  1. a
  2. b
  3. nothing will print

Most of you will think of the 3rd option because you can see the condition is not true and hence the statement under if will not execute. Your concept is not wrong, you are right here but probably you miss the semicolon ( ; ) that is placed just after if statement in the programs. if statement ends here and the followed lines are not under the if statement, it’s a free line and it’s execution does not depend on any conditional statement.

option 1 is the correct answer.

Mistake No 2

Look at the program given below:

int main() 
char c = 'a'; 
if ( c = 'b' ) 
printf("The value of c is %c", c); 

What will be the output of this program ?
  1. The value of c is a.
  2. The value of c is b.
  3. Nothing will print

If your answer is 3, probably you missed the β€˜ = β€˜ assignment operator in the if statement. it’s not conditional operator, so it will not compare the values but it will assign the constant at right hand side to the variable at left hand side and hence the value that come in β€˜ if statement β€˜ is a non-zero value hence this program will print something.

If your answer is 1, I would like to congratulate you because you noticed the β€˜=’ assignment operator in the if statement but there is one thing that you forget that assignment operator not only make the if statement un-effective but also update the value of c from β€˜a’ to β€˜b’ and hence the option 2 is the correct answer.

Mistake No. 3

Look at the program given below:

int main() 
char c='a'; 
if (c == 'b') 
printf("Statement A "); 
printf("Statement B "); 
printf("Test me "); 

What will be the output of this program ?

  1. Statement A Statement B Test me
  2. Statement B Test me
  3. Test me

if your answer is 1. probably you do not know anything about if statement otherwise you will never select this option, condition is false so how can β€œStatement A” will print?

if your answer is 3. obviously you know about the if statement but you just choosen a wrong answer because you just beleive in indent (space) that is given to the 6th statement with the intention to make you fool.

if statement takes more then one statement β€˜ if and only if β€˜ statements are surrounded by the β€˜ { β€˜ β€˜ } β€˜ curly braces. so 6th statement is out of the block of if statement and do not depend on if statement. So the correct answer is 2.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top