Surfing the net and looking for other people's codes, I've seen a 1 or true
but I really do not know what the purpose of this is.
while(1){
CODIGO AQUI!
}
Surfing the net and looking for other people's codes, I've seen a 1 or true
but I really do not know what the purpose of this is.
while(1){
CODIGO AQUI!
}
The while 1
is not used at all in specific except to allow the unlimited execution of the content of the cycle, its equivalent in any of its derivatives would be:
while (true) {
// Código aquí.
}
It will keep running what is in the loop until you put some condition that makes it come out with a break
or something similar.
In C, it is common to use while (1)
to make this clear: "There is no logical condition that is accurate to stop this cycle"
For example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF (1024)
int main(void) {
int c = 0, ind = 0; char str[MAX_BUF];
while (1) {
printf("Escribe algo (No mas de 1024 caracteres): ");
ind = 0; /* Reseteamos el indice. */
while (((c = fgetc(stdin)) != '\n) && (ind < MAX_BUF))
str[ind] = c, ind++;
if (0 == strcmp(str, "salir")) /* Salimos si es necesario. */
break;
if (ind) /* Nos aseguramos que el usuario no presiono enter nomas. */
printf("Has escrito: '%s'\n", str);
}
return 0;
}
Notice that in the previous code, you will only exit the cycle if the variable str
contains the value "salir"
, in the same way you can put more than one condition for the exit of the cycle, but while none is fulfilled, it will just keep running.
In fact, you can try to do a while (1)
and see how your program never ends. : ^)
Greetings:)
The purpose of this code is to create an infinite loop.
In the real world, the most common use is to prevent another block code from being reached, whether a code block is reached outside that loop, an error has occurred or it enters the loop if an error has occurred.
The second type of use being that which has been given to a file that is part of the linux kernel and can be appreciated on line 678 of the file pc_keyb.c in version 2.4.x.