IF Statement


                         The if statement helps in making decisions. The statements accompanying the if statement is termed as if block (Recall that block starts with '{' and ends with '}' ). The syntax of this statements is:

                   if (condition)
                   {
                             expressions/statements to be evaluated;
                    }

                           When the compilers encounters the if statement, the condition is executed and if it is  false, it returns a zero to if, and if it is true, it returns a positive value (Scroll down for more explanation on this). So whenever the if statement gets a zero(false) as return value, the expressions in it are omitted i.e they are not executed and the control goes to the end of the if block. And, if the condition returns positive value, i.e if it is true, the statements inside the block get executed.

Let's look at an example:


#include <stdio.h>

int  main() 
{

    int  a = 5, b = 10;
    
    if (b > a)
    {
        printf ("b is greater!\n");
    }
 
    if (a = printf("Test statement\n")){
  
        printf ("%d", a);
    }
    
    return 0;


}

Output:

Explanation:

  • b > a returns 1, therefore, the printf statement in the if block is executed.
  • printf("Test statement\n") returns 15, the length of the string argument. 
Latest
Previous
Next Post »