best practice on precedence of variable declaration and error handling in C
- by guest
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!