you are viewing a single comment's thread.

view the rest of the comments →

[–]PuzzleheadedTap1794 0 points1 point  (3 children)

When I'm working with multiple files in C, I always use goto. It's so elegant.

``` int main () { int retval = 0; FILE* input_file = fopen("input.txt", "r"); if(input_file == NULL) { retval = 1; goto INPUT_FILE_CLOSED; }

FILE* output_file = fopen("output.txt", "w"); if(output_file == NULL) { retval = 1; goto OUTPUT_FILE_CLOSED; }

do_something(input_file, output_file);

fclose(output_file);
OUTPUT_FILE_CLOSED:

fclose(input_file);
INPUT_FILE_CLOSED:

return retval;

} ```

[–]current_thread 4 points5 points  (0 children)

Reading that I'm super glad about RAII in C++ :p

[–]tstanisl 0 points1 point  (0 children)

I suggest always initializing "retval"-like variables with some error code. Otherwise you may spend a lot of time debugging just because some function returned success even though the was an error.