×

C++ Infinite loop

The term "infinite loop" refers to a loop that does not terminate the loop according to the condition. In some cases, an infinite loop may be required in programming, or a loop may become infinite when the exit condition becomes false again and again.

Applications

An infinite loop is useful for programs that receive user input and continuously generate output until the user exits the program manually.

The infinite loop can be utilized in the following scenarios:

1) If you're developing an application that allows the user to submit the long data having the loop 30,000 or 300,000,000 times. The code run infinitely and receiving the user input until the user presses Ctrl-C to terminate the application.

2) If you have a constant monitoring operation running on your servers.

3) As the server answers all client requests, it runs in an eternal loop. It breaks the endless cycle when the administrator manually shuts down the server.

4) When your server script listens for connections on a socket, this could be a useful feature.

5) Infinite loops are frequently used in video game programming.

There are various loop structures in C that can be used to produce an infinite loop. Following are the looping structures that define the endless loop:

  • For loop
  • While loop
  • Do-While loop

Infinite For Loop

A condition in for loop terminates the loop. The condition can be left blank if we wanted. We may also remove the initialization and repeat statements from the for loop. These fields are optional and can be left empty. Because the condition will never be false, the control will never exit the loop, which produce an infinite loop.

For loop syntax

for (
  <initial statement(s)>;
  <Condition expression>;
  <Repeat step(s)>
      )
{
  <Loop statement(s)>;
}

Infinite For loop:

for(;;);
     for(;;)
         {
            }

Infinite For Loop with True for Condition

For loop uses a boolean expression that evaluates the condition to be true or false. Instead of giving an expression, we can substitute the boolean value “true” for the condition which results an infinite loop.

Program:

#include <iostream>
using namespace std;
 int main()
 {
   for (; true; ) 
     {
      cout << "javaTpoint" << endl;
   }
}

Output:

javaTpoint
javaTpoint
javaTpoint
javaTpoint
javaTpoint
..
..
..

The string ‘’javaTpoint” will print at a time on the console infinitely. To terminate the execution of the program press CTRL and C together on the keyboard.

Infinite while loop in C

There is a condition statement in the while loop. This is a required expression that cannot be omitted. As a result, we must provide a true condition here. "TRUE", "1", "1==1", and so on are the TRUE statements.

While loop syntax

while (<Condition expression>)
{
  <Loop statement(s)>;
}

Infinite While loop

while (1);


while (1)
     {
       }

Infinite While Loop with TRUE condition

You can use a condition that always evaluates to true. But, you cannot use a TRUE boolean value in the condition of the while loop for infinite loop. The criterion 1 == 1 or 0 == 0 is always true.
The condition is always true and the loop will While loop run infinitely.

Program:

#include <iostream>
using namespace std;
 int main()
 {
While(1==1)
{
      cout << "javaTpoint" << endl;
   }
}

Output:

javaTpoint
javaTpoint
javaTpoint
javaTpoint
javaTpoint
..
..

The string “javaTpoint” prints one by one infinitely as the given condition is always true. To terminate the execution of the program press CTRL+C on the keyboard.


Infinite Do-While loop:

There is a condition statement in the while loop. This is a required expression that cannot be omitted. As a result, we must provide a true condition here. "TRUE", "1", "1==1", and so on are the TRUE statements.

Do-While loop syntax

do
{
  <Loop statement(s)>;
} while (<Condition expression>);

Infinite Do-While loop:

do {
      } while(1);

Infinite do-while Loop with No Update to Control Variables

When you forget to update the variables involved in the condition, you can end up with infinite loops.   

We have set variable “i” to 0 in the below example and want to print a string to the console until the value of i becomes 10.

In the example below, we would not use the update statement to increment ”i” for printing javaTpoint 10 times. So, the value of i would never change and the code will run infinitely with value of i. This result in an infinite do-while loop.

Program:

#include <iostream>
using namespace std;
 int main()
 {
i=0;
do
{
      cout << "javaTpoint" << endl;
   }while(i<10)
}

Output:

javaTpoint
javaTpoint
javaTpoint
javaTpoint
javaTpoint
..
..

Long Running Loops

It's recommended to add some delay to each loop. Otherwise, the process may consume all CPU cycles and cause the system to freeze. This may be required when the programmer is waiting for a condition to occur. A sleep statement releases the task to the scheduler and allowing other tasks to continue normally. This statement causes the current thread to suspend execution for a specified period.

For Loop;

for(;;)
{
Sleep(1);
}

While Loop:

while(1)
{
  Sleep(1);
}

Do-While Loop:

do
{
  Sleep(1);
}
while(1);

Debug infinite loops

A program enters an infinite loop and continue to execute the body of the loop. This type of problem may not occur very often and may occur due to a rare instance. On the other hand, these problems are simple to troubleshoot or debug.

We should write the break statement for checking the condition from where the loop become infinite. To get to the root of the problem, we need to figure out why the condition isn't becoming false.


Related Topics

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.