Function scope
suggest changeFunction scope is the special scope for labels. This is due to their unusual property. A label is visible throughout the function in which it is defined, and goto label can jump to it from any point in that function. The following example illustrates the point, even though the control flow is not useful:
#include <stdio.h>
int main(int argc,char *argv[]) {
int a = 0;
goto INSIDE;
OUTSIDE:
if (a!=0) {
int i=0;
INSIDE:
printf("a=%d\n",a);
goto OUTSIDE;
}
}
INSIDE may seem to be defined inside the if block, as i is, but it is not. It is visible in the whole function, as goto INSIDE; shows. A function therefore cannot contain two labels with the same name.
One practical use is a cleanup ladder for allocated resources:
#include <stdlib.h>
#include <stdio.h>
void a_function(void) {
double* a = malloc(sizeof(double[34]));
if (!a) {
fprintf(stderr,"can't allocate\n");
return; /* No point in freeing a if it is null */
}
FILE* b = fopen("some_file","r");
if (!b) {
fprintf(stderr,"can't open\n");
goto CLEANUP1; /* Free a; no point in closing b */
}
/* do something reasonable */
int error = 0; /* A real function sets this when the operation fails. */
if (error) {
fprintf(stderr, "something's wrong\n");
goto CLEANUP2; /* Free a and close b to prevent leaks. */
}
/* do yet something else */
CLEANUP2:
fclose(b);
CLEANUP1:
free(a);
}
Labels such as CLEANUP1 and CLEANUP2 are special identifiers that behave differently from all other identifiers. They are visible from everywhere inside the function, even in places that are executed before the labeled statement, or even in places that could never be reached if none of the goto is executed. Labels are often written in lower-case rather than upper-case.