Search code examples
c++functionreturnturbo-c++unreachable-code

Why is this program showing "unreachable code" warning? And how do I suppress it?


#include<iostream.h>
#include<conio.h>
#include<process.h>

void function(void);

int main(void)
{
 clrscr();

 int ch;

 while(1)
 {
  cin>>ch;

  if(ch==2)
    exit(0);
  else
    function();
 }//while
 return 0;
}//main

void function(void)
{
 cout<<"Hello";

 return;
}

The above code is working fine, but why I'm getting the "unreachable code" warning? I really don't understand what am I doing wrong. The compiler shows no warning when I comment/remove the return 0; statement in main(). Why is it so? Please tell me what is it that I'm doing wrong and what is the correct way to do it.


Solution

  • The while (1) loop has no option to leave.

    Thereby, the exit(0) is not recognized as the dataflow analysis doesn't consider it as an option to jump to code behind of while (1) (and actually it doesn't).

    Hence, there is no way to get to the return 0;.

    If you replace exit(0) by a break than it changes. The break will cause to leave the while (1) and the return 0; becomes reachable.