How to use goto for error handling in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>

int goto_error_handling() {
    int result = 0; 

    FILE* f = fopen("logfile.txt", "w+");

    if (!f) {
        return -1;
    }

    if (fputs("logfile line 1", f) == EOF) {
        result = -2;
        goto out;
    }

    // your code...

    // Releasing resources 
out:
    if (fclose(f) == EOF) {
        result = -3;
    }

    return result;
}

int main()
{
    printf("%d\n", goto_error_handling());

    return 0;
}




/*
run:

0

*/

 



answered Nov 28, 2024 by avibootz
edited Nov 28, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

int goto_error_handling() {
    int result = 0;

    allocate_resources_1();

    if (!init(values)) {
        goto error_1;
    }

    allocate_resources_2();

    if (!read_date()) {
        goto error_2;
    }

    allocate_resources_3();

    if (!query(values)) {
        goto error_3;
    }

    result = your_code(values);

error_3:
    cleanup_3();
error_2:
    cleanup_2();
error_1:
    cleanup_1();
        
    return result;
}

int main()
{
    printf("%d\n", goto_error_handling());

    return 0;
}




/*
run:


*/

 



answered Nov 28, 2024 by avibootz

Related questions

2 answers 247 views
1 answer 207 views
2 answers 327 views
327 views asked Sep 26, 2020 by avibootz
1 answer 160 views
...