yurich
yurich

Reputation: 175

How to make immutability a default behaviour with C preprocessor

I think that the benefits of data immutability outweigh the inconvenience of the implicit mut qualifier. That's why in my opinion it should be the default. I know that some functional languages implement types like this and Rust also does that.

The problem is, I can't figure out how to use C preprocessor to achive that. Specifically, I'd like do these replacements:

typename     -> typename const
typename_mut -> typename

I tried using naive defines:

#define int const int
#define int_mut int

However, this makes everything const. Swapping position changes nothing. How else could I approach that?

Update (additional info)

Naive version:

#define char const char
#define char_mut char

int main() {
    char_mut integer = 5;
    integer = 6;
}

expands to:

// gcc -E main.c
// # 0 "main.c"
// # 0 "<built-in>"
// # 0 "<command-line>"
// # 1 "main.c"

int main() {
    const char integer = 5;
    integer = 6;
}

Upvotes: 1

Views: 121

Answers (0)

Related Questions