1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

int round_down(int n, int multiple_of) {
    // ARGUMENTS are the variables that were passed on.  They are
    // declared by the function signature itself.
    // ∙ n
    // ∙ multiple_of
    //
    // LOCAL VARIABLES are declared in the body of the function.
    // ∙ n_rounded_down
    //
    // They exist (i.e., there is space for them) the moment we enter
    // that function.

    int n_rounded_down = (n * multiple_of) / multiple_of; // BUG!!!

    // int n;  // ← variable DECLARATION
    // n = 5;  // ← variable INITIALIZATION (first time value is assigned)
    //
    // In ECE 26400, you should always declare where you initialize.
    // 
    // BAD:
    //    int n;
    //    n = 5;
    //
    // GOOD:
    //    int n = 5;  // we declared the variable at the point where we
    //                // first «need» to assign to it.
    //
    // Do not initialize with dummy values like this:
    //
    // BAD:
    //    int n = 0;
    //    n = 5;

    return n_rounded_down;
}

int main(int argc, char* argv[]) {
    int n = 7;
    int divisor = 3;  // aka "multiple_of"
    int n_rounded_down_to_nearest_multiple_of_divisor = round_down(n, divisor);

    printf("round_down(7, 3) == %d  (expected: 6)\n",
            n_rounded_down_to_nearest_multiple_of_divisor);

    return EXIT_SUCCESS;
}

// int n_rounded_down = (n / multiple_of) * multiple_of; // CORRECT

/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2022 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.