best practice on precedence of variable declaration and error handling in C
Posted
by guest
on Stack Overflow
See other posts from Stack Overflow
or by guest
Published on 2010-06-13T11:45:30Z
Indexed on
2010/06/13
11:52 UTC
Read the original article
Hit count: 295
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!
© Stack Overflow or respective owner