Reputation: 1801
I've been asked to break down a C program which initially was just one main method with a lot of well commented segments. Each segment makes use of this same defined function string, 'die', if an error occurs. The die function uses the goto label, 'out', which shuts down the program.
After turning each one of these segments into a function which are all now called from the scaled down main method at the bottom, this goto out code of each segment no longer works. The 'out' label is within the main and the XCode compiler is telling me that the goto label hasn't been defined.
So I guess I'm asking how do I define my out label in each of these local functions, in the most efficient manner?
Here are some code snippets, all in the order/structure they appear:
Die defined
#define die(msg, ...) do { \
(void) fprintf (stderr, msg, ## __VA_ARGS__); \
(void) fprintf (stderr, "\n"); \
goto out; \
} while (0)
An example of a function using die
void createContext(void){
context = clCreateContext (0, 1, &device_id, NULL, NULL, &err);
if (!context || err != CL_SUCCESS)
die ("Error: Failed to create a compute context!");
}
Finally my main, which contains the out label from die at the end
main (int argc, char *argv[])
{
(Several functions called here)
out:
/* Shutdown and cleanup. */
if (data)
free (data);
if (results)
free (results);
return rc;
}
Upvotes: 1
Views: 3643
Reputation: 409482
A goto
can not span functions. If you use goto
it has to be to a label within the same function as the goto
.
To do a jump between functions, look up the setjmp
and longjmp
functions.
However, in your case since you are just jumping to exit the program, you can call exit
directly instead. All resources (open files, allocated memory) will be released by the runtime library and the operating system.
Upvotes: 9