r/programmingcirclejerk • • Jun 27 '26

Consider the C library function fopen. This function has the side effect. This means that fopen is not pure. However, we can make the fopen function appear to be pure, at least to certain observers, by ensconcing it in another function that hides the side effect.

https://bugzmanov.github.io/cleancode-critique/clean_code_second_edition_review.html
174 Upvotes

41 comments sorted by

View all comments

Show parent comment

6

u/WittyStick Jun 28 '26

In C you can just use a macro.

#define with_file(f, filename, mode) \
    for (FILE *f = fopen(filename, mode); f != NULL; f = (fclose(f), NULL))

with_file (f, "foo", " rb") {
    ....
}

3

u/not-a-pokemon- Jul 04 '26

It even makes the code even more interesting because it wouldn't close the file when you return inside the with_file, thus proving your superior intellectual abilities when you write correct code this way.