logo

Oändlig loop i C

Vad är oändlig loop?

En oändlig loop är en loopingkonstruktion som inte avslutar loopen och exekverar loopen för alltid. Det kallas också en obestämd slinga eller en ändlös slinga. Den ger antingen en kontinuerlig utmatning eller ingen utmatning.

När ska man använda en oändlig loop

En oändlig loop är användbar för de applikationer som accepterar användarinmatningen och genererar utgången kontinuerligt tills användaren lämnar applikationen manuellt. I följande situationer kan denna typ av loop användas:

listnod i java
  • Alla operativsystem körs i en oändlig slinga eftersom det inte existerar efter att ha utfört någon uppgift. Det kommer ut ur en oändlig loop endast när användaren manuellt stänger av systemet.
  • Alla servrar körs i en oändlig loop när servern svarar på alla klientförfrågningar. Det kommer ut ur en obestämd loop endast när administratören stänger av servern manuellt.
  • Alla spelen körs också i en oändlig loop. Spelet kommer att acceptera användarens önskemål tills användaren lämnar spelet.

Vi kan skapa en oändlig loop genom olika loopstrukturer. Följande är slingstrukturerna genom vilka vi kommer att definiera den oändliga slingan:

  • för slinga
  • medan loop
  • gör-under loop
  • gå till uttalande
  • C makron

För loop

Låt oss se oändlig 'för' slinga. Följande är definitionen för oändlig för loop:

 for(; ;) { // body of the for loop. } 

Som vi vet att alla delar av 'för' loop är valfria, och i ovanstående för loop har vi inte nämnt något villkor; så denna loop kommer att köras oändligt många gånger.

Låt oss förstå genom ett exempel.

 #include int main() { for(;;) { printf('Hello javatpoint'); } return 0; } 

I ovanstående kod kör vi 'för'-loopen oändligt många gånger, så 'Hej javatpoint' kommer att visas oändligt.

Produktion

Oändlig loop i C

medan loop

Nu kommer vi att se hur man skapar en oändlig loop med hjälp av en while-loop. Följande är definitionen för infinite while-slingan:

 while(1) { // body of the loop.. } 

I den ovanstående while-slingan sätter vi '1' i loop-tillståndet. Som vi vet representerar vilket heltal som helst som inte är noll det sanna villkoret medan '0' representerar det falska villkoret.

Låt oss titta på ett enkelt exempel.

 #include int main() { int i=0; while(1) { i++; printf('i is :%d',i); } return 0; } 

I ovanstående kod har vi definierat en while-loop, som körs oändligt många gånger eftersom den inte innehåller något villkor. Värdet på 'i' kommer att uppdateras ett oändligt antal gånger.

Produktion

Oändlig loop i C

gör.. medan loop

De göra medan loop kan också användas för att skapa den oändliga loopen. Följande är syntaxen för att skapa det oändliga göra medan slinga.

 do { // body of the loop.. }while(1); 

Ovanstående do..while loop representerar det oändliga tillståndet eftersom vi tillhandahåller '1'-värdet inuti loopvillkoret. Eftersom vi redan vet att heltal som inte är noll representerar det sanna villkoret, så kommer denna loop att köras oändligt många gånger.

goto uttalande

Vi kan också använda goto-satsen för att definiera den oändliga slingan.

 infinite_loop; // body statements. goto infinite_loop; 

I koden ovan överför goto-satsen kontrollen till den oändliga slingan.

Makron

Vi kan också skapa den oändliga slingan med hjälp av en makrokonstant. Låt oss förstå genom ett exempel.

 #include #define infinite for(;;) int main() { infinite { printf('hello'); } return 0; } 

I koden ovan har vi definierat ett makro som heter 'oändligt', och dess värde är 'för(;;)'. Närhelst ordet 'oändlig' kommer i ett program kommer det att ersättas med ett 'för(;;)'.

Produktion

Oändlig loop i C

Hittills har vi sett olika sätt att definiera en oändlig loop. Men vi behöver något tillvägagångssätt för att komma ut ur den oändliga loopen. För att komma ut ur den oändliga slingan kan vi använda break-satsen.

Låt oss förstå genom ett exempel.

 #include int main() { char ch; while(1) { ch=getchar(); if(ch=='n') { break; } printf('hello'); } return 0; } 

I koden ovan har vi definierat while-loopen, som kommer att köras ett oändligt antal gånger tills vi trycker på tangenten 'n'. Vi har lagt till 'if'-satsen i while-slingan. 'if'-satsen innehåller nyckelordet break, och nyckelordet break ger kontrollen ut ur loopen.

om annat java

Oavsiktliga oändliga loopar

Ibland uppstår situationen där oavsiktliga oändliga loopar uppstår på grund av buggen i koden. Om vi ​​är nybörjare blir det väldigt svårt att spåra dem. Nedan följer några åtgärder för att spåra en oavsiktlig oändlig loop:

  • Vi bör undersöka semikolon noggrant. Ibland sätter vi semikolonet på fel ställe, vilket leder till den oändliga slingan.
 #include int main() { int i=1; while(i<=10); { printf('%d', i); i++; } return 0; < pre> <p>In the above code, we put the semicolon after the condition of the while loop which leads to the infinite loop. Due to this semicolon, the internal body of the while loop will not execute.</p> <ul> <li>We should check the logical conditions carefully. Sometimes by mistake, we place the assignment operator (=) instead of a relational operator (= =).</li> </ul> <pre> #include int main() { char ch=&apos;n&apos;; while(ch=&apos;y&apos;) { printf(&apos;hello&apos;); } return 0; } </pre> <p>In the above code, we use the assignment operator (ch=&apos;y&apos;) which leads to the execution of loop infinite number of times.</p> <ul> <li>We use the wrong loop condition which causes the loop to be executed indefinitely.</li> </ul> <pre> #include int main() { for(int i=1;i&gt;=1;i++) { printf(&apos;hello&apos;); } return 0; } </pre> <p>The above code will execute the &apos;for loop&apos; infinite number of times. As we put the condition (i&gt;=1), which will always be true for every condition, it means that &apos;hello&apos; will be printed infinitely.</p> <ul> <li>We should be careful when we are using the <strong>break</strong> keyword in the nested loop because it will terminate the execution of the nearest loop, not the entire loop.</li> </ul> <pre> #include int main() { while(1) { for(int i=1;i<=10;i++) { if(i%2="=0)" break; } return 0; < pre> <p>In the above code, the while loop will be executed an infinite number of times as we use the break keyword in an inner loop. This break keyword will bring the control out of the inner loop, not from the outer loop.</p> <ul> <li>We should be very careful when we are using the floating-point value inside the loop as we cannot underestimate the floating-point errors.</li> </ul> <pre> #include int main() { float x = 3.0; while (x != 4.0) { printf(&apos;x = %f
&apos;, x); x += 0.1; } return 0; } </pre> <p>In the above code, the loop will run infinite times as the computer represents a floating-point value as a real value. The computer will represent the value of 4.0 as 3.999999 or 4.000001, so the condition (x !=4.0) will never be false. The solution to this problem is to write the condition as (k<=4.0).< p> <p> <strong> <em>Infinite loops</em> </strong> can cause problems if it is not properly <strong> <em>controlled</em> </strong> or <strong> <em>designed</em> </strong> , leading to excessive <strong> <em>CPU resource consumption</em> </strong> and unresponsiveness in programs or systems. <strong> <em>Implementing mechanisms</em> </strong> to break out of infinite loops is crucial when necessary.</p> <p>It is advisable to include <strong> <em>exit conditions</em> </strong> within the <strong> <em>loop</em> </strong> to prevent unintentional infinite loops. These conditions can be based on <strong> <em>user input</em> </strong> , <strong> <em>specific events or flags</em> </strong> , or <strong> <em>time limits</em> </strong> . The loop will terminate by incorporating appropriate <strong> <em>exit conditions</em> </strong> after fulfilling its purpose or meeting specific criteria.</p> <h2>Techniques for Preventing Infinite Loops:</h2> <p>Although <strong> <em>infinite loops</em> </strong> can occasionally be intended, they are frequently <strong> <em>unintended</em> </strong> and can cause program <strong> <em>freezes</em> </strong> or <strong> <em>crashes</em> </strong> . Programmers can use the following strategies to avoid inadvertent infinite loops:</p> <p> <strong>Add a termination condition:</strong> Make sure the loop has a condition that can ultimately evaluate to <strong> <em>false</em> </strong> , allowing it to <strong> <em>end</em> </strong> .</p> <p> <strong>Employ a counter:</strong> Establish a cap on the number of iterations and implement a counter that increases with each loop iteration. Thus, even if the required condition is not satisfied, the loop will ultimately come to an <strong> <em>end</em> </strong> .</p> <p> <strong>Introduce a timeout system:</strong> If the time limit is reached, the <strong> <em>loop</em> </strong> will be stopped. Use a timer or system functions to measure the amount of time that has passed.</p> <p> <strong>Use external or user-provided triggers:</strong> Design the loop to end in response to certain user input or outside events.</p> <p>In certain cases, <strong> <em>infinite loops</em> </strong> may be intentionally employed in specialized algorithms or <strong> <em>system-level operations</em> </strong> . For instance, real-time systems or embedded systems utilize infinite loops to monitor inputs or execute specific tasks continuously. However, care must be taken to manage such <strong> <em>loops properly</em> </strong> , avoiding any adverse effects on system performance or responsiveness.</p> <p>Modern programming languages and development frameworks often offer built-in mechanisms to handle infinite loops more efficiently. For example, <strong> <em>Graphical user interface (GUI) frameworks</em> </strong> provide event-driven architectures where programs wait for user input or system events, eliminating the need for explicit infinite loops.</p> <p>It is essential to exercise caution and discretion when using <strong> <em>infinite loops</em> </strong> . They should only be employed when there is a clear and valid reason for an indefinite running loop, and adequate safeguards must be implemented to prevent any negative impact on the program or system.</p> <h2>Conclusion:</h2> <p>In conclusion, an <strong> <em>infinite loop</em> </strong> in C constitutes a looping construct that never ends and keeps running forever. Different <strong> <em>loop structures</em> </strong> , such as the <strong> <em>for loop, while loop, do-while loop, goto statement, or C macros</em> </strong> , can be used to produce it. Operating systems, servers, and video games all frequently employ infinite loops since they demand constant human input and output until manual termination. On the other hand, the <strong> <em>unintentional infinite loops</em> </strong> might happen because of code flaws, which are difficult to identify, especially for newcomers.</p> <p>Careful consideration of <strong> <em>semicolons, logical criteria</em> </strong> , and <strong> <em>loop termination</em> </strong> requirements is required to prevent inadvertent infinite loops. Infinite loops can result from improper semicolon placement or the use of assignment operators in place of relational operators. False loop conditions that always evaluate to true may likewise result in an <strong> <em>infinite loop</em> </strong> . Furthermore, since the <strong> <em>break keyword</em> </strong> only ends the closest loop, caution must be used when using it in nested loops. Furthermore, as they may make the loop termination condition impossible to meet, floating-point mistakes should be considered while working with floating-point numbers.</p> <hr></=4.0).<></p></=10;i++)></pre></=10);>

I ovanstående kod använder vi tilldelningsoperatorn (ch='y') som leder till exekvering av loop oändligt många gånger.

full adderare krets
  • Vi använder fel loopvillkor vilket gör att loopen exekveras på obestämd tid.
 #include int main() { for(int i=1;i&gt;=1;i++) { printf(&apos;hello&apos;); } return 0; } 

Ovanstående kod kommer att exekvera 'for loop' oändligt många gånger. Som vi uttrycker villkoret (i>=1), som alltid kommer att vara sant för varje villkor, betyder det att 'hej' kommer att skrivas ut i oändlighet.

  • Vi bör vara försiktiga när vi använder ha sönder nyckelordet i den kapslade loopen eftersom det kommer att avsluta exekveringen av den närmaste loopen, inte hela loopen.
 #include int main() { while(1) { for(int i=1;i<=10;i++) { if(i%2="=0)" break; } return 0; < pre> <p>In the above code, the while loop will be executed an infinite number of times as we use the break keyword in an inner loop. This break keyword will bring the control out of the inner loop, not from the outer loop.</p> <ul> <li>We should be very careful when we are using the floating-point value inside the loop as we cannot underestimate the floating-point errors.</li> </ul> <pre> #include int main() { float x = 3.0; while (x != 4.0) { printf(&apos;x = %f
&apos;, x); x += 0.1; } return 0; } </pre> <p>In the above code, the loop will run infinite times as the computer represents a floating-point value as a real value. The computer will represent the value of 4.0 as 3.999999 or 4.000001, so the condition (x !=4.0) will never be false. The solution to this problem is to write the condition as (k<=4.0).< p> <p> <strong> <em>Infinite loops</em> </strong> can cause problems if it is not properly <strong> <em>controlled</em> </strong> or <strong> <em>designed</em> </strong> , leading to excessive <strong> <em>CPU resource consumption</em> </strong> and unresponsiveness in programs or systems. <strong> <em>Implementing mechanisms</em> </strong> to break out of infinite loops is crucial when necessary.</p> <p>It is advisable to include <strong> <em>exit conditions</em> </strong> within the <strong> <em>loop</em> </strong> to prevent unintentional infinite loops. These conditions can be based on <strong> <em>user input</em> </strong> , <strong> <em>specific events or flags</em> </strong> , or <strong> <em>time limits</em> </strong> . The loop will terminate by incorporating appropriate <strong> <em>exit conditions</em> </strong> after fulfilling its purpose or meeting specific criteria.</p> <h2>Techniques for Preventing Infinite Loops:</h2> <p>Although <strong> <em>infinite loops</em> </strong> can occasionally be intended, they are frequently <strong> <em>unintended</em> </strong> and can cause program <strong> <em>freezes</em> </strong> or <strong> <em>crashes</em> </strong> . Programmers can use the following strategies to avoid inadvertent infinite loops:</p> <p> <strong>Add a termination condition:</strong> Make sure the loop has a condition that can ultimately evaluate to <strong> <em>false</em> </strong> , allowing it to <strong> <em>end</em> </strong> .</p> <p> <strong>Employ a counter:</strong> Establish a cap on the number of iterations and implement a counter that increases with each loop iteration. Thus, even if the required condition is not satisfied, the loop will ultimately come to an <strong> <em>end</em> </strong> .</p> <p> <strong>Introduce a timeout system:</strong> If the time limit is reached, the <strong> <em>loop</em> </strong> will be stopped. Use a timer or system functions to measure the amount of time that has passed.</p> <p> <strong>Use external or user-provided triggers:</strong> Design the loop to end in response to certain user input or outside events.</p> <p>In certain cases, <strong> <em>infinite loops</em> </strong> may be intentionally employed in specialized algorithms or <strong> <em>system-level operations</em> </strong> . For instance, real-time systems or embedded systems utilize infinite loops to monitor inputs or execute specific tasks continuously. However, care must be taken to manage such <strong> <em>loops properly</em> </strong> , avoiding any adverse effects on system performance or responsiveness.</p> <p>Modern programming languages and development frameworks often offer built-in mechanisms to handle infinite loops more efficiently. For example, <strong> <em>Graphical user interface (GUI) frameworks</em> </strong> provide event-driven architectures where programs wait for user input or system events, eliminating the need for explicit infinite loops.</p> <p>It is essential to exercise caution and discretion when using <strong> <em>infinite loops</em> </strong> . They should only be employed when there is a clear and valid reason for an indefinite running loop, and adequate safeguards must be implemented to prevent any negative impact on the program or system.</p> <h2>Conclusion:</h2> <p>In conclusion, an <strong> <em>infinite loop</em> </strong> in C constitutes a looping construct that never ends and keeps running forever. Different <strong> <em>loop structures</em> </strong> , such as the <strong> <em>for loop, while loop, do-while loop, goto statement, or C macros</em> </strong> , can be used to produce it. Operating systems, servers, and video games all frequently employ infinite loops since they demand constant human input and output until manual termination. On the other hand, the <strong> <em>unintentional infinite loops</em> </strong> might happen because of code flaws, which are difficult to identify, especially for newcomers.</p> <p>Careful consideration of <strong> <em>semicolons, logical criteria</em> </strong> , and <strong> <em>loop termination</em> </strong> requirements is required to prevent inadvertent infinite loops. Infinite loops can result from improper semicolon placement or the use of assignment operators in place of relational operators. False loop conditions that always evaluate to true may likewise result in an <strong> <em>infinite loop</em> </strong> . Furthermore, since the <strong> <em>break keyword</em> </strong> only ends the closest loop, caution must be used when using it in nested loops. Furthermore, as they may make the loop termination condition impossible to meet, floating-point mistakes should be considered while working with floating-point numbers.</p> <hr></=4.0).<></p></=10;i++)>

I ovanstående kod kommer slingan att köras oändligt många gånger eftersom datorn representerar ett flyttalsvärde som ett verkligt värde. Datorn kommer att representera värdet 4,0 som 3,999999 eller 4,000001, så villkoret (x !=4,0) kommer aldrig att vara falskt. Lösningen på detta problem är att skriva villkoret som (k<=4.0).< p>

Oändliga slingor kan orsaka problem om det inte är korrekt kontrollerade eller designad , vilket leder till överdriven CPU resursförbrukning och bristande respons i program eller system. Genomförandemekanismer att bryta sig ur oändliga loopar är avgörande när det behövs.

Det är lämpligt att inkludera utgångsförhållanden inom slinga för att förhindra oavsiktliga oändliga loopar. Dessa förutsättningar kan baseras på användarinmatning , specifika händelser eller flaggor , eller tidsbegränsningar . Slingan kommer att avslutas genom att inkorporera lämpliga utgångsförhållanden efter att ha uppfyllt sitt syfte eller uppfyllt specifika kriterier.

Tekniker för att förhindra oändliga loopar:

Fastän oändliga slingor kan ibland vara avsedda, de är ofta oavsiktlig och kan orsaka program fryser eller kraschar . Programmerare kan använda följande strategier för att undvika oavsiktliga oändliga loopar:

Lägg till ett uppsägningsvillkor: Se till att slingan har ett tillstånd som i slutändan kan utvärderas till falsk , tillåter det slutet .

Använd en räknare: Sätt ett tak för antalet iterationer och implementera en räknare som ökar med varje loop-iteration. Således, även om det erforderliga villkoret inte är uppfyllt, kommer slingan slutligen att komma till en slutet .

Introducera ett timeout-system: Om tidsgränsen nås, slinga kommer att stoppas. Använd en timer eller systemfunktioner för att mäta hur lång tid som har gått.

Använd externa eller av användaren tillhandahållna utlösare: Designa slingan så att den slutar som svar på viss användarinmatning eller externa händelser.

I vissa fall, oändliga slingor kan avsiktligt användas i specialiserade algoritmer eller verksamhet på systemnivå . Till exempel använder realtidssystem eller inbyggda system oändliga loopar för att övervaka indata eller utföra specifika uppgifter kontinuerligt. Man måste dock se till att hantera sådana slingor ordentligt , för att undvika negativa effekter på systemets prestanda eller lyhördhet.

Moderna programmeringsspråk och utvecklingsramverk erbjuder ofta inbyggda mekanismer för att hantera oändliga loopar mer effektivt. Till exempel, Ramverk för grafiskt användargränssnitt (GUI). tillhandahålla händelsedrivna arkitekturer där program väntar på användarinmatning eller systemhändelser, vilket eliminerar behovet av explicita oändliga loopar.

Det är viktigt att iaktta försiktighet och diskretion vid användning oändliga slingor . De bör endast användas när det finns ett tydligt och giltigt skäl för en obestämd löpslinga, och adekvata skyddsåtgärder måste implementeras för att förhindra negativ påverkan på programmet eller systemet.

Slutsats:

Sammanfattningsvis en oändlig loop i C utgör en looping-konstruktion som aldrig tar slut och som fortsätter att fungera för alltid. Annorlunda slingstrukturer , så som för loop, while loop, do-while loop, goto statement eller C makron , kan användas för att producera den. Operativsystem, servrar och videospel använder ofta oändliga loopar eftersom de kräver konstant mänsklig input och output tills manuell avslutning. Å andra sidan oavsiktliga oändliga loopar kan hända på grund av kodfel, som är svåra att identifiera, särskilt för nykomlingar.

Noggrant övervägande av semikolon, logiska kriterier , och slingavslutning krav krävs för att förhindra oavsiktliga oändliga loopar. Oändliga loopar kan vara resultatet av felaktig placering av semikolon eller användning av tilldelningsoperatorer i stället för relationsoperatorer. Falska loopvillkor som alltid utvärderas till sanna kan på samma sätt resultera i en oändlig loop . Dessutom, eftersom bryt nyckelord slutar endast den närmaste slingan, försiktighet måste iakttas när den används i kapslade slingor. Dessutom, eftersom de kan göra villkoret för slingavslutning omöjligt att uppfylla, bör flyttalsmisstag beaktas när man arbetar med flyttal.