try-catch vs setjmp-longjmp
ANSI C does not support try-catch block like C++. Alternatively it supports setjmp-longjmp which is similar to a try-catch block.
setjmp-longjmp uses variable type jmp_buf to store return context of setjmp to be used by longjmp at error condition. setjmp saves the CPU context in the buffer and returns 0. Afterwards if some error occurs, program calls logjmp which restores the last saved context. Thus the CPU again jumps to previous context of setjmp and now setjmp returns a non-zero value and it goes to the exception path. Following example will illustrate this concept.
int setjmp(jmp_buf context);
Saves the environment into the variable 'context'. If a non-zero value is returned, then this indicates that the point in the source code was reached by a longjmp. Otherwise zero is returned indicating the context has been saved in 'context'.
void longjmp(jmp_buf context, int value);
Causes the 'context' to be restored from a setjmp call where the environment variable had been saved. It causes the execution to jump to the setjmp location as if setjmp had returned the value of the variable 'value'. The variable 'value' cannot be zero. However, if zero is passed, then it is replaced by 1. If the function where setjmp was called has terminated, then the results are undefined.
setjmp-longjmp - source code
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Learn on Youtube