title: Optimizing neighbor count function for conway's game of life in C
body: <p>Having some trouble optimizing a function that returns the number of neighbors of a cell in a Conway's Game of Life implementation. I'm trying to learn C and just get better at coding. I'm not very good at recognizing potential optimizations, and I've spent a lot of time online reading various methods but it's not really clicking for me yet. </p>
  
  <p>Specifically I'm trying to figure out how to unroll this nested for loop in the most efficient way, but each time I try I just make the runtime longer. 
  I'm including the function, I don't think any other context is needed. Thanks for any advice you can give!</p>
  
  <p>Here is the code for the <code>countNeighbors()</code> function:</p>
  
  <pre><code>static int countNeighbors(board b, int x, int y)
  {
     int n = 0;
  
     int x_left = max(0, x-1);
     int x_right = min(HEIGHT, x+2);
     int y_left = max(0, y-1);
     int y_right = min(WIDTH, y+2);
  
     int xx, yy;
     for (xx = x_left; xx &lt; x_right; ++xx) {
         for (yy = y_left; yy &lt; y_right; ++yy) {
             n += b[xx][yy];
         }
     }
  
     return n - b[x][y];
  }
  </code></pre>