Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C while loop only runs if statement true?

I was looking at some C code and I found this line.

if (temp==NULL)
    while (1) ;

From my understanding when you get into a infinite loop there is no getting out unless you break, how does this work? does it break when if statement is not NULL if so, what makes it keep checking the if statement over and over again?

For more information look for the realboy source code the file is gboy_lcd.c

Line 304
https://github.com/guilleiguaran/realboy/blob/ed30dee751c3f78964e71930a8f87d2074362b9b/gboy_lcd.c

It's a very stable and good gameboy emulator though for linux

like image 964
SSpoke Avatar asked Dec 06 '22 02:12

SSpoke


2 Answers

basically somebody is halting the program. If temp is NULL then the program will go into an infinite loop on the while statement. I would expect to see a comment in the code saying why he is doing this.

This is very common in embedded / micro code (ie the code running your TV set, fridge, smoke detector,...) because there is no way to stop / crash / alert. The only thing you can do is loop. During development you can use a debugger to break into the code to see whats happening

PS - why the downvotes - this is a good question

like image 113
pm100 Avatar answered Dec 08 '22 16:12

pm100


This code starts a while loop if temp is NULL.

The while loop evaluates the expression (1) over and over and does nothing each time until 1 != 1 which will never happen.

Written more clearly with Allman bracing shows it:

if (temp == NULL)
{
    while(1)
    {
    }
}

As pointed out in a comment, this version shows that the if is not part of the while.

like image 38
Almo Avatar answered Dec 08 '22 16:12

Almo