In the past when I've done this:

int function(int a)
{
  if(a == 2)
  {
  return true;
  }
  else
  {
  return false;
  }
}

the compiler has complained that the function may not return a value. I've fixed this by adding:

int function(int a)
{
  if(a == 2)
  {
  return true;
  }
  else
  {
  return false;
  }

  return false;
}

but now a different compiler is complaining that the last line is "unreachable code" (which I agree with). How is this usually handled?

Thanks,

David

Sorry, I made the example too simple - maybe something more like:

int function(int a)
{
  if(a == 2)
  {
  // do something
  return true;
  }
  else
  {
  // do something else
  return false;
  }
}

I guess even this can be changed to what you suggested:

int function(int a)
{
  if(a == 2)
  {
  // do something
  return true;
  }

  // do something else
  return false;
}

Interesting... it doesn't look as clear to the reader at first glance (at least to me) but I suppose it fixes the problem... :)

or like this, where there is only one return statement

bool function(int a)
{
   bool rvalue = false;
   if(a == 2)
   {
      // do something
      rvalue = true;
   }
   else
   {
      // do something else
      rvalue = false;
   }
   return rvalue;
}

Edited 6 Years Ago by Ancient Dragon: n/a

Which problem? The one where it doesn't know that all return paths actually do return a value? I'm not sure actually - I haven't seen it in a while and I can't reproduce it now, I've just seen it in the past so I was trying to prevent it. But all the suggestions here certainly help me do that - thanks all.

Problem 1 :

bool isFoo(){
 if(condition1){ return true; }
 else return false;
}

Modern compiler shouldn't complain about this. If they do, you can just ignore it.

This question has already been answered. Start a new discussion instead.