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
#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[]) {
    // data segment strings are read only at runtime
    char* data_str = "Hello";
    log_str(data_str);
    // not allowed to modify: seg fault
    //data_str[1] = 'a';
    log_str(data_str);

    // we are free to modify stack allocated strings
    char stack_str[] = "Hello";
    char* a_stack_str0 = stack_str;
    log_str(stack_str);
    a_stack_str0[1] = 'a';
    log_str(stack_str);

    // const strings are read only at compile time
    char const* const_stack_str = stack_str;
    stack_str[3] = 'p';
    // not allowed to modify: compiler error
    //const_stack_str[1] = 'e';
    log_str(const_stack_str);

    // its good practice to declare a data segment string as const
    // as a reminder to us that it cannot be modifed
    // this means the compiler will catch your bug instead of an
    // unfortunate user (or grader) running your program
    char const* const_data_str = "Hello";
    // declared data string in a way the compiler will catch me
    // trying to modify it
    //const_data_str[1] = 'a';
    log_str(const_data_str);

    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.