best practice on the precedent of variable declaration and error handling in C

advertisements

is there an advantage in one of the following two approaches over the other?

here it is first tested, whether fopen succeeds at all and then all the variable declarations take place, to ensure they are not carried out, since they mustn't have had to

void func(void) {
    FILE *fd;

    if ((fd = fopen("blafoo", "+r")) == NULL ) {
          fprintf(stderr, "fopen() failed\n");
          exit(EXIT_FAILURE);
    }

    int a, b, c;
    float d, e, f;
    /* variable declarations */

    /* remaining code */
}

this is just the opposite. all variable declarations take place, even if fopen fails

void func(void) {
    FILE *fd;
    int a, b, c;
    float d, e, f;
    /* variable declarations */

    if ((fd = fopen("blafoo", "+r")) == NULL ) {
          fprintf(stderr, "fopen() failed\n");
          exit(EXIT_FAILURE);
    }

    /* remaining code */
}

does the second approach produce any additional cost, when fopen fails? would love to hear your thoughts!


No, it doesn't have any cost. Both examples most likely compile to the same resulting binary. Since variable declaration without assignment doesn't actually do anything in C, it doesn't generate any code. The space available for those variables will be simply skipped over by the stack pointer when needed.