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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

typedef struct _Node {
    int value;
    struct _Node* next;
} Node;

int main(int argc, char* argv[]) {
    // Places where you a need a typecast.

    // 1. Internal calculations where you need to truncate before doing next operation.
    double dollar_amt = 0.75599;  // suppose you want just 0.
    int truncated = ((int)(dollar_amt * 100) / 100) ;  // ... or something like that
    //                    └────────────────┘

    // 2. Internal calculation where you need the right type before you use ▒->▒.
    void* address_of_something = _get_address_of_something();
    //int value_of_node = address_of_something -> value;  // ERROR
    int value_of_node = ((Node*)address_of_something) -> value;

    // 3. Internal calculation where you need the right type before you use *.
    //Node node_object = *address_of_something;  // ERROR
    Node node_object = *((Node*)address_of_something);

    // 4. printf("%p") -- %p requires void*, not ▒▒▒▒*
    Node* new_node = _create_node(5);
    printf("new_node == %p\n", (void*)new_node);

    // 5. va_arg(char*)
    char* s = (char*)va_arg(variadic_arguments, char*);

    // DO NOT USE TYPECAST JUST TO GET RID OF A COMPILER WARNING, unless you know for sure…
    // ∙ It is safe,
    // ∙ It is necessary,
    // ∙ … and why.
    
    // BAD USES
    char* s = "abc";

    //void* address_of_something = (void*)s;  // BAD!!! … unnecessary typecast
    void* address_of_something = s;  // GOOD because void* ↔ ▒▒▒▒*

    //char* t = (char*)address_of_something;  // BAD!!! … unnecessary typecast
    char* t = address_of_something;  // GOOD because void* ↔ ▒▒▒▒*

    //Node* new_node = (Node*)malloc(sizeof(*new_node)); // BAD!!! … unnecessary typecast
    Node* new_node = malloc(sizeof(*new_node)); // GOOD

    char* s = "abc";
    char** a_s = &s;
    char* t = a_s;   // BUG... but gcc will tell us with a helpful error.
                     //        (a_s is a char** but t is a char*.  They are incompatible.)
    //char* t = (char*)a_s;   // TERRIBLE:  Do not use typecast to silence error/warning,
    //                        //            unless it is safe, necessary, and you know why.

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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