Debian Codegraph @

example/methods/iterate.c

raw
1 /*
2 * methods/iterate.c
3 *
4 * Calculate the sum of a given range of integer numbers.
5 *
6 * This particular method of implementation works by way of brute force,
7 * i.e. it iterates over the entire range while adding the numbers to finally
8 * get the total sum. As a positive side effect, we're able to easily detect
9 * overflows, i.e. situations in which the sum would exceed the capacity
10 * of an integer variable.
11 *
12 */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <limits.h>
17 #include "iterate.h"
18
19 void test_data_logging(int, int);
20
21 int iterate_get_sum (int min, int max)
22 {
23 int i, total;
24
25 test_data_logging(min, max);
26
27 total = 0;
28
29 /* This is where we loop over each number in the range, including
30 both the minimum and the maximum number. */
31
32 for (i = min; i <= max; i++)
33 {
34 /* We can detect an overflow by checking whether the new
35 sum would exceed the maximum integer value. */
36
37 if (total > INT_MAX - i)
38 {
39 printf ("Error: sum too large!\n");
40 exit (1);
41 }
42
43 /* Everything seems to fit into an int, so continue adding. */
44
45 total += i;
46 }
47
48 return total;
49 }
50
51 void
52 test_data_logging(int min, int max)
53 {
54 (void)min; /* quiet compiler complaints */
55 (void)max;
56 printf("this is some debug data logging code that gets removed in the final product\n");
57 }