1. Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.
    Dismiss Notice

difference between loop and conditional statement in c

Discussion in 'Microcontrollers' started by Parth86, Aug 14, 2017.

  1. Parth86

    Parth86 Member

    Joined:
    Dec 25, 2011
    Messages:
    546
    Likes:
    5
    Hi all
    generally I understand what is while loop and conditional statement (if else ). but I am confused on when do we use while loop and conditional statement in c programming.

    Code (c):

    while (condition)
    {
       statements;
    }
     
    if the condition is true loop will run infinite and condition is false loop will never run


    Code (c):

    if (/* condition goes here */)
    {
       /* if the condition is true, this code will execute */
     }

     else {
       /* if the condition is false, this code will execute */
     }
     
    what is use of this type of structure

    Code (c):


    do nothing

    while (condition1)
      {

      }
    while (condition2)                              

      {

      }
     
     
  2. ci139

    ci139 Active Member

    Joined:
    Apr 12, 2012
    Messages:
    470
    Likes:
    37
  3. Pommie

    Pommie Well-Known Member Most Helpful Member

    Joined:
    Mar 18, 2005
    Messages:
    10,161
    Likes:
    340
    Location:
    Brisbane Australia
    In Microcontrollers you never want to return from main and so an infinite while(1) loop is the best solution. Depending on the application I may run the main code 50 times a second by waiting for a timer to time out like so,
    Code (text):

        while(1){            //loop forever
            while(!TMR2IF);    //wait for timer
            TMR2IF=0;
     
            //main code would be here
     
        }//end main loop
    The bit TMR2IF is set automatically by the hardware.

    The if(condition) construct is used to only do something when something is true. An example would be if a byte has been received by the RS232 module,
    Code (text):

            if(RCIF){
         
                //code here to handle the received byte
         
            }//end if
    Again, RCIF is set by the hardware when a byte is received.

    Mike.
     

Share This Page