logo

Bucle infinit en C

Què és el bucle infinit?

Un bucle infinit és una construcció de bucle que no acaba el bucle i executa el bucle per sempre. També s'anomena an indefinit bucle o an sense fi bucle. O bé produeix una sortida contínua o cap sortida.

Quan utilitzar un bucle infinit

Un bucle infinit és útil per a aquelles aplicacions que accepten l'entrada de l'usuari i generen la sortida contínuament fins que l'usuari surt de l'aplicació manualment. En les situacions següents, es pot utilitzar aquest tipus de bucle:

declaració javascript if
  • Tots els sistemes operatius funcionen en un bucle infinit ja que no existeix després de realitzar alguna tasca. Només surt d'un bucle infinit quan l'usuari tanca manualment el sistema.
  • Tots els servidors s'executen en un bucle infinit mentre el servidor respon a totes les peticions del client. Només surt d'un bucle indefinit quan l'administrador tanca el servidor manualment.
  • Tots els jocs també funcionen en un bucle infinit. El joc acceptarà les sol·licituds de l'usuari fins que l'usuari surti del joc.

Podem crear un bucle infinit a través de diverses estructures de bucle. Les següents són les estructures de bucle a través de les quals definirem el bucle infinit:

  • per bucle
  • bucle while
  • bucle do-while
  • anar al comunicat
  • macros C

Per bucle

Vegem el infinit 'per' bucle. La següent és la definició de infinit bucle per:

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

Com sabem que totes les parts del bucle 'for' són opcionals, i en el bucle for anterior, no hem esmentat cap condició; per tant, aquest bucle s'executarà infinites vegades.

Entenem-ho a través d'un exemple.

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

Al codi anterior, executem el bucle 'for' infinites vegades, per tant 'Hola javatpoint' es mostrarà infinitament.

Sortida

Bucle infinit en C

bucle while

Ara, veurem com crear un bucle infinit mitjançant un bucle while. La següent és la definició del bucle while infinit:

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

Al bucle while anterior, posem '1' dins de la condició de bucle. Com sabem que qualsevol nombre enter diferent de zero representa la condició vertadera mentre que '0' representa la condició falsa.

Vegem un exemple senzill.

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

En el codi anterior, hem definit un bucle while, que s'executa infinites vegades ja que no conté cap condició. El valor de 'i' s'actualitzarà un nombre infinit de vegades.

Sortida

Bucle infinit en C

do..while bucle

El Fer mentre bucle també es pot utilitzar per crear el bucle infinit. La següent és la sintaxi per crear l'infinit Fer mentre bucle.

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

El fet anterior, mentre que el bucle representa la condició infinita, ja que proporcionem el valor '1' dins de la condició de bucle. Com ja sabem que un nombre enter diferent de zero representa la condició real, per tant, aquest bucle s'executarà infinites vegades.

anar a declaració

També podem utilitzar la instrucció goto per definir el bucle infinit.

 infinite_loop; // body statements. goto infinite_loop; 

Al codi anterior, la instrucció goto transfereix el control al bucle infinit.

Macros

També podem crear el bucle infinit amb l'ajuda d'una constant macro. Entenem-ho a través d'un exemple.

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

En el codi anterior, hem definit una macro anomenada 'infinit' i el seu valor és 'for(;;)'. Sempre que la paraula 'infinit' aparegui en un programa, es substituirà per un 'per (;;)'.

convertir nombre enter en cadena java

Sortida

Bucle infinit en C

Fins ara, hem vist diverses maneres de definir un bucle infinit. Tanmateix, necessitem algun enfocament per sortir del bucle infinit. Per sortir del bucle infinit, podem utilitzar la instrucció break.

Entenem-ho a través d'un exemple.

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

En el codi anterior, hem definit el bucle while, que s'executarà un nombre infinit de vegades fins que premem la tecla 'n'. Hem afegit la instrucció 'if' dins del bucle while. La sentència 'si' conté la paraula clau break, i la paraula clau break treu el control fora del bucle.

Bucles infinits no intencionats

De vegades es produeix la situació en què es produeixen bucles infinits no intencionats a causa de l'error del codi. Si som els principiants, llavors es fa molt difícil rastrejar-los. A continuació es mostren algunes mesures per traçar un bucle infinit no intencionat:

  • Hem d'examinar els punts i coma amb atenció. De vegades posem el punt i coma al lloc equivocat, la qual cosa condueix al bucle infinit.
 #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);>

En el codi anterior, utilitzem l'operador d'assignació (ch='y') que condueix a l'execució de bucles infinites vegades.

  • Utilitzem la condició de bucle incorrecta que fa que el bucle s'executi indefinidament.
 #include int main() { for(int i=1;i&gt;=1;i++) { printf(&apos;hello&apos;); } return 0; } 

El codi anterior executarà el 'bucle for' un nombre infinit de vegades. Com posem la condició (i>=1), que sempre serà certa per a cada condició, vol dir que 'hola' s'imprimirà infinitament.

  • Hem d'anar amb compte quan fem servir el trencar paraula clau al bucle imbricat perquè finalitzarà l'execució del bucle més proper, no tot el bucle.
 #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++)>

Al codi anterior, el bucle s'executarà infinites vegades, ja que l'ordinador representa un valor de coma flotant com a valor real. L'ordinador representarà el valor de 4,0 com a 3,999999 o 4,000001, de manera que la condició (x !=4,0) no serà mai falsa. La solució a aquest problema és escriure la condició com (k<=4.0).< p>

Bucles infinits pot causar problemes si no és correctament controlat o dissenyat , donant lloc a un excés Consum de recursos de la CPU i manca de resposta en programes o sistemes. Mecanismes d'aplicació sortir dels bucles infinits és crucial quan cal.

S'aconsella incloure condicions de sortida dins de bucle per evitar bucles infinits no intencionats. Aquestes condicions es poden basar en entrada de l'usuari , esdeveniments o banderes concrets , o límits de temps . El bucle finalitzarà incorporant l'adequada condicions de sortida després de complir la seva finalitat o complir uns criteris específics.

Tècniques per prevenir bucles infinits:

Encara que bucles infinits ocasionalment poden ser pensats, són freqüents no desitjat i pot provocar un programa es congela o accidents . Els programadors poden utilitzar les estratègies següents per evitar bucles infinits inadvertits:

Afegiu una condició de terminació: Assegureu-vos que el bucle tingui una condició que finalment es pugui avaluar fals , permetent-ho final .

Fes servir un comptador: Establiu un límit en el nombre d'iteracions i implementeu un comptador que augmenta amb cada iteració del bucle. Així, fins i tot si no es compleix la condició requerida, el bucle finalment arribarà a un final .

Introduïu un sistema de temps d'espera: Si s'arriba al límit de temps, el bucle s'aturarà. Utilitzeu un temporitzador o funcions del sistema per mesurar la quantitat de temps que ha passat.

Utilitzeu activadors externs o proporcionats per l'usuari: Dissenyeu el bucle perquè finalitzi en resposta a determinades entrades de l'usuari o esdeveniments externs.

En determinats casos, bucles infinits es pot utilitzar intencionadament en algorismes especialitzats o operacions a nivell de sistema . Per exemple, els sistemes en temps real o els sistemes incrustats utilitzen bucles infinits per supervisar les entrades o executar tasques específiques contínuament. Tanmateix, s'ha de tenir cura de gestionar-los bucles correctament , evitant qualsevol efecte advers sobre el rendiment o la capacitat de resposta del sistema.

Els llenguatges de programació moderns i els marcs de desenvolupament sovint ofereixen mecanismes integrats per gestionar bucles infinits de manera més eficient. Per exemple, Frameworks d'interfície gràfica d'usuari (GUI). proporcionar arquitectures basades en esdeveniments on els programes esperen l'entrada de l'usuari o els esdeveniments del sistema, eliminant la necessitat de bucles infinits explícits.

arquitectura java

És essencial tenir precaució i discreció a l'hora d'utilitzar bucles infinits . Només s'han d'utilitzar quan hi ha una raó clara i vàlida per a un cicle d'execució indefinit, i s'han d'implementar les garanties adequades per evitar qualsevol impacte negatiu en el programa o sistema.

Conclusió:

En conclusió, an bucle infinit en C constitueix una construcció en bucle que no s'acaba mai i continua funcionant per sempre. Diferent estructures de bucle , com ara el bucle for, bucle while, bucle do-while, declaració goto o macros C , es pot utilitzar per produir-lo. Els sistemes operatius, els servidors i els videojocs solen emprar bucles infinits, ja que exigeixen una entrada i sortida humana constants fins a la finalització manual. D'altra banda, el bucles infinits no intencionats pot passar a causa de defectes de codi, que són difícils d'identificar, especialment per als nouvinguts.

Consideració acurada de punt i coma, criteris lògics , i terminació del bucle es requereixen requisits per evitar bucles infinits inadvertits. Els bucles infinits poden resultar d'una col·locació inadequada de punt i coma o de l'ús d'operadors d'assignació en lloc d'operadors relacionals. Les condicions de bucle fals que sempre s'avaluen com a vertaderes també poden donar lloc a un bucle infinit . A més, des del la paraula clau trenca només acaba el bucle més proper, cal tenir precaució quan l'utilitzeu en bucles imbricats. A més, com que poden fer que la condició de terminació del bucle sigui impossible de complir, els errors de coma flotant s'han de considerar quan es treballa amb nombres de coma flotant.