Author Topic: exit clause on infinite loop  (Read 7075 times)

Offline ggpevans

  • New Member
  • Posts: 1
exit clause on infinite loop
« on: July 10, 2012, 08:31:14 AM »
Hello, just a quick question.

I was told in an embedded micro controller subject I did, if
programming in the C language you should use an infinite
for loop with no arguments eg. for( ; ; )

The program runs forever.

I cant get nasm installed just yet, but lets say you build an object file
(full of assembly) that acts like an OS, do you still put the
'exit' statement in the assembly language (nasm) code?

How else would you get it to run forever (until turned off)

Many thanks
Greg

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: exit clause on infinite loop
« Reply #1 on: July 10, 2012, 11:08:21 AM »
Code: [Select]
; ---
begin:
; get a command from the user
; do what it says
; is it an exit command?
    cmp al, 'X'
    je exit
    jmp begin

exit:
; print "press any key to reboot"?
    int 19h

You can include macros to give you stuff like "for", but the underlying instructions are "jmp", unconditional, and conditional jumps collectively known as "jcc". There's "je", jump if equal, "jne", jump if not equal, jg, jump if greater... like that.

If it's going to "act like an OS", it has to do a bit more than get commands from the user, of course, but that's the idea. When you get to the end, go back and do it again... or whatever you want it to do until it's turned off.

Best,
Frank


Offline TightCoderEx

  • Full Member
  • **
  • Posts: 103
Re: exit clause on infinite loop
« Reply #2 on: July 10, 2012, 11:54:57 AM »
I often contemplate with great interest, what was being discussed in the 30 minutes or so, that finally led to the statement "You should do this.  As a matter of fact.

Code: [Select]
for (;;) { }
while (1) {}
do {} while (1)

and

Loop:
   goto Loop;

In the "C" language are functionally the same. You may not be aware too, that exit is not a "C" language keyword, but a higher level construct somewhat implementation specific.

I'm assuming maybe you've studied the PIC series of controllers of which I am somewhat familiar, but the need for infinite loops in an OS, like Linux, OSX and Windows is not required.  Multi tasking operating systems like these function much different than the linearity of a micro controller. But;

In NASM
Code: [Select]
Next:  jmp Next

or even

        jmp $

Are examples of infinite loops in NASM.

When you say until "turned off, this is where the IA-32 or 64 architecture is different than on a PIC controller as an example, BUT if you were to use an Intel chip for a garage door controller let say. You'd find the HLT - Halt instruction a more viable option versus infinite loops.
« Last Edit: July 10, 2012, 11:59:38 AM by TightCoderEx »