How to Create a While Loop in C

Create a while loop any time your C program needs to iterate over values or variables. With a few simple precautions, while loops can be easy and powerful.

Instructions

  1. Understand the Conditions

    • 1

      Remember that every while loop has a condition which determines when it ends. The loop repeats as long as the condition is true. Conditions usually involve comparisons between variables, like:

      while (temperature < 212) {
      temperature = increase_heat(temperature);
      }

    • 2

      Program your loop to either evaluate the condition at the start or end. Evaluating at the start is the more common case, as in the previous example. Evaluating at the end ensures that the loop will happen at least once:

      do {
      temperature = next_temperature();
      } while (temperature < 212);

    • 3

      Aim for the truth: It's vital that the condition eventually become true, to avoid an infinite loop. Be sure the body of the loop, the part inside curly brackets, includes something that changes variables involved in the conditions, and that they'll eventually make the condition false.

    • 4

      Accept the ability of C to include an assignment inside a condition, which can sometimes make your code shorter and less repetitive. For example:

      while ((temperature = next_temperature()) < 212) {
      update_sensor_logs(temperature);
      }

    Break Out of the Loop

    • 5

      Break out. Inside the body of a while loop, you can break out of the loop immediately, whether the condition is false or not. Simply use the break command:

      while (temperature < 212) {
      if (!sensor_detected()) break;
      temperature = increase_heat(temperature);
      }

    • 6

      Force the loop to jump back to the condition and re-evaluate it using the continue command:

      while (temperature < 212) {
      temperature = next_temperature();
      if (sensor_error()) continue;
      sensor_changes++;
      }

Tips & Warnings

  • The for loop is just a shorthand to a while loop with a preceding initialization and an integral iteration step. Most C compilers create the same code from for and while loops.

  • Usually, optimizing a program for speed means focusing on what happens inside its while loops, especially those which are nested.

  • A while loop whose condition never becomes false can lock up your program and the entire computer it's running on.

  • Avoid loops that do nothing while they wait for a condition to be met, called "busy-wait loops." These can grind all other programs to a halt and prevent the condition they're waiting for from ever happening, a condition called "deadlock." If your operating system can't create an event trigger, at least use its functions to cede control back to it inside the loop body.

Related Searches

You May Also Like

Related Ads

Featured
View Mobile Site