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

I just write:

if( 2 == a )
    return true;

return false;

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;
}

The problem you suggested should be fixed by modern compilers. Which one are you using?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.