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

#define log_str(n) printf("%s == %s\n", (#n), (n))

int main(int argc, char* argv[]) {
    char char_array[] = "hello";
    char* non_const_str = char_array;
    // &char_array[0] would work the same

    // original value
    log_str(non_const_str);
    // we can modify characters in the string
    non_const_str[1] = 'a';
    log_str(non_const_str);
    // can swap the string for another address
    non_const_str = "world";
    log_str(non_const_str);
    log_str(char_array);

    // const char* const_value_str = char_array;
    // meanss the same thing as:
    char const* const_value_str = char_array;
    // cannot modify
    //        \_______________/
    //        * const_value_str
    log_str(const_value_str);
    // not allowed: cannot modify characters in the string
    //const_value_str[1] = 'e';
    const_value_str = "word";
    // can assign directly to const_value_st
    log_str(const_value_str);

    char* const const_address_str = char_array;
    // cannot modify
    //          \_______________/
    //          const_address_str
    log_str(const_address_str);
    // can modify data in the string
    const_address_str[1] = 'o';
    log_str(const_address_str);
    // cannot assign to another address
    //const_address_str = "different string entirely";
    
    char const* const fully_const_str = char_array;
    // cannot modify address or value
    // cannot modify *fully_const_str or fully_const_str
    // cannot modify data in the string
    //fully_const_str[2] = 't';
    // cannot set equal to another string
    //fully_const_str = "another string";
    
    // tip: read type of const from right to left

    // if we had a char **, 3 spots for const
    //  char const **
    //  char* const *
    //  char** const

    return EXIT_SUCCESS;
}
/* 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.