Monday, April 27, 2015

1. IF
Syntax:

 if(boolean_expression)  
 {  
   /* statement(s) will execute if the boolean expression is true */  
 }  

Điều kiện sẽ true khi boolean expression non-zero hoặc non-null


Flow:

Ex: 
if.c
 #include <stdio.h>  
 int main()  
 {  
   int a = 0;  
   int *pa = NULL;  
   //NON-ZERO  
   if(a){  
     printf("line<%d> a = %d \n", __LINE__, a);  
   }  
   a= 5;  
   if(a){  
     printf("line<%d> a = %d \n", __LINE__, a);  
   }  
   //NON-NULL  
   if(pa) {  
     printf("line<%d> *pa = %d \n", __LINE__, *pa);  
   }  
   pa = &a;  
   if(pa) {  
     printf("line<%d> *pa = %d \n", __LINE__, *pa);  
   }  
   return 0;  
 }  

Compile & Execute
 $ gcc if.c  
 $ ./a.out   
 line<16> a = 5   
 line<25> *pa = 5   

2. IF ... ELSE
Syntax:
 if(boolean_expression)  
 {  
   /* statement(s) will execute if the boolean expression is true */  
 }  
 else  
 {  
  /* statement(s) will execute if the boolean expression is false */  
 }  

Flow:

IF ... ELSE IF ... ELSE
Syntax:
 if(boolean_expression 1)  
 {  
   /* Executes when the boolean expression 1 is true */  
 }  
 else if( boolean_expression 2)  
 {  
   /* Executes when the boolean expression 2 is true */  
 }  
 else if( boolean_expression 3)  
 {  
   /* Executes when the boolean expression 3 is true */  
 }  
 else   
 {  
   /* executes when the none of the above condition is true */  
 }  

3. SWITCH
Syntax:
 switch(expression){  
   case constant-expression :  
     statement(s);  
     break; /* optional */  
   case constant-expression :  
     statement(s);  
     break; /* optional */  
   /* you can have any number of case statements */  
   default : /* Optional */  
     statement(s);  
 }  

Flow:
Ex:
 #include <stdio.h>  
 int main ()  
 {  
   /* local variable definition */  
   char grade = 'B';  
   switch(grade)  
   {  
   case 'A' :  
    printf("Excellent!\n" );  
    break;  
   case 'B' :  
   case 'C' :  
    printf("Well done\n" );  
    break;  
   case 'D' :  
    printf("You passed\n" );  
    break;  
   case 'F' :  
    printf("Better try again\n" );  
    break;  
   default :  
    printf("Invalid grade\n" );  
   }  
   printf("Your grade is %c\n", grade );  
   return 0;  
 }  


4. The ?: operator

 retExp = Exp1 ? Exp2 : Exp3;  

Nếu Exp1 true thì retExp = Exp2 không thì retExp = Exp3

 if(Exp1){  
     retExp = Exp2;  
 }else{  
     retExp = Exp3;  
 }  

Ex:
 #include <stdio.h>  
 int main()  
 {  
   int a = 0;  
   int b;  
   b = (a > 5) ? 5:a;  
   printf("a = %d, b = %d\n", a, b);  

   //The same as  
   if(a > 0){  
     b = 5;   
   } else {  
     b = a;  
   }  
   printf("a = %d, b = %d\n", a, b);  
   return 0;  
 }  



Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Lập trình hệ thống nhúng Linux . Powered by Luong Duy Ninh -