Answer SL46

Familiar Global Bug


Seems to be a problem


PS C:\Source>gcc sumVersion6.c 
PS C:\Source>a
sum of 1..10: 55
sum of 1..5: 70
PS C:\Source>

Comments:

It looks as if the sum of 1 to 5 is greater than the sum of 1 to 10. Something is wrong!

Of course, what is wrong is that the global variable sum retains the value that the first call to the function computed. Then the second call adds to that left-over value.

The function computed the correct result the first time! Casual debugging might have looked no further and not caught the bug.

The rule, of course, is to initialize variables and to keep them as local as possible.


 
/* --- sumVersion6.c --- */
#include <stdio.h>

int j;
int sum = 0;  /* keeps its value between calls */

int sumInts( int limit )
{
  
  for ( j=1; j<=limit; j++ )
    sum += j;
    
  return sum;
}
 
void main()
{   
  int sum = sumInts( 10 );
  printf( "sum of 1..10: %d\n", sum );    

  sum = sumInts( 5 );
  printf( "sum of 1..5: %d\n", sum );    
}


Back to Puzzle Home