user61050: I always see while(1); at the end of the C codes such as:
#include <stdio.h>


int main(void)
{

    //Some code here...

    while(1);

}

If I'm not wrong that it always exists, what is the function of that?
edit:
#include <stdio.h>


int main(void)
{


     while(1);
    //Some code here...



}


user4143: It's because in non-embedded systems, when main() finishes it returns to the operating system and the program is removed from memory. In embedded systems there's no operating system to return to, and the program can't be removed from memory.  So... what do you do when the program is finished?  Simple: you do nothing. Forever.  And that's what while(1); does.
Some compilers and C libraries automatically add while(1); in the exit() routine, but not all do - so it's better to do it explicitly than rely on something that may or may not be there.

61050: <p>I always see while(1); at the end of the C codes such as:</p>

<pre><code>#include &lt;stdio.h&gt;


int main(void)
{

    //Some code here...

    while(1);

}
</code></pre>

<p>If I'm not wrong that it always exists, what is the function of that?</p>

<p>edit:</p>

<pre><code>#include &lt;stdio.h&gt;


int main(void)
{


     while(1);
    //Some code here...



}
</code></pre>
 4143: <p>It's because in non-embedded systems, when <code>main()</code> finishes it returns to the operating system and the program is removed from memory. In embedded systems there's no operating system to return to, and the program can't be removed from memory.  So... what do you do when the program is finished?  Simple: you do nothing. Forever.  And that's what <code>while(1);</code> does.</p>

<p>Some compilers and C libraries automatically add <code>while(1);</code> in the <code>exit()</code> routine, but not all do - so it's better to do it explicitly than rely on something that may or may not be there.</p>
