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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

// This is from a question that was asked after class.

typedef struct _Rectangle {
    int x1;
    int y1;
    int x2;
    int y2;
    bool is_valid;
} Rectangle;

/*
Rectangle make_rectangle(int x1, int y1, int x2, int y2) {  // method 0:  BAD
    // For ECE 26400, you must initialize all fields using a named initializer or
    // set alll fields at once using a compound literal, unless there is an
    // articulable reason why you can't or shouldn't.  Setting fields individually is
    // more error-prone.
    Rectangle rect;
    if(x1 == x2 || y1 == y2) {  // width==0 or height==0
        rect.x1 = 0;
        rect.x2 = 0;
        rect.y1 = 0;
        rect.y2 = 0;
        rect.is_valid = false;
    }
    else {
        rect.x1 = x1;
        rect.x2 = x2;
        rect.y1 = y1;
        rect.y2 = y2;
        rect.is_valid = false;
    }
    return rect;
}

Rectangle make_rectangle(int x1, int y1, int x2, int y2) {  // method 1:  okay, not best
    if(x1 == x2 || y1 == y2) {  // width==0 or height==0
        // Declare and initialize with a named initializer.
        Rectangle rect = { .x1=0, .y1=0, .x2=0, .y2=0, .is_valid=false };
        return rect;
    }
    else {
        // Declare and initialize with a named initializer.
        Rectangle rect = { .x1=x1, .y1=y1, .x2=x2, .y2=y2, .is_valid=true };
        return rect;
    }
}

Rectangle make_rectangle(int x1, int y1, int x2, int y2) {  // method 2:  okay, not best
    Rectangle rect;  // Declare
    if(x1 == x2 || y1 == y2) {  // width==0 or height==0
        // Set all fields of struct object using compound literal
        rect = (Rectangle) { .x1=0, .y1=0, .x2=0, .y2=0, .is_valid=false };
    }
    else {
        rect = (Rectangle) { .x1=x1, .y1=y1, .x2=x2, .y2=y2, .is_valid=true };
    }
    return rect;
}
*/

Rectangle make_rectangle(int x1, int y1, int x2, int y2) {  // method 3:  AQ's favorite
    if(x1 == x2 || y1 == y2) {  // width==0 or height==0
        // Return struct object directly using a compound literal.
        return (Rectangle) { .x1=0, .y1=0, .x2=0, .y2=0, .is_valid=false };
    }
    else {
        return (Rectangle) { .x1=x1, .y1=y1, .x2=x2, .y2=y2, .is_valid=true };
    }
}



int main(int argc, char* argv[]) {
    
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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