csetjmp

Using the setjmp and longjmp


Having such a simple C code

#include <stdio.h>
#include <setjmp.h>

void Com_Error(int);

jmp_buf abortframe;

int main() {
    
    if (setjmp (abortframe)){
        printf("abortframe!\n");
        return 0;           
    }
    
    Com_Error(0);
    
    printf("main end\n");    
    return 0;
}

void Com_Error(int code) {
    // ...
    longjmp (abortframe, code);
    //...
}

I'm getting:

abortframe!

My question is WHY does it prints the abortframe! if we pass 0 (NOT true) and hence the condition if (setjmp (abortframe)){...} should NOT be meet so no abortframe! string printed?


Solution

  • Read the friendly manual (C17 7.13.2.1):

    The longjmp function cannot cause the setjmp macro to return the value 0; if val is 0, the setjmp macro returns the value 1.