Programming Puzzle no. 1

On the train to work a few days ago, I came up with the following little puzzle, based on several real-life programming experiences of working on code recently. See what you think.

The following method works correctly and produces the correct output. However, after several years of modifications by numerous different software engineers, nobody knows quite what it does any more, and everybody is too scared to modify it.

Simplify the method without altering the output of the program. the method as it stands can be considered bug free, and logically correct. Also, the method is called in a single threaded application – there are no worries with concurrency.
// global variable, holds it's value between calls of func
int a = 0;

int func(int b, unsigned int c)
{
  int d = 0;
  int n = 1;

  if(c < 0)
  {
    d = a * (0 - c);
  }
  else
  {
    d = a;
  }

  a = a * a;

  if(b == -1)
  {
    for(int e = 0; e < n; ++e)
    {
      ++d;
    }
  }
  else
  {
    d = b * n;
  }

  a = d;

  return a;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>