2

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?

Lundin
  • 195,001
  • 40
  • 254
  • 396
darro911
  • 136
  • 6
  • 1
    You mustn't pass `0` in `longjmp`. See [man setjmp](https://man7.org/linux/man-pages/man3/setjmp.3.html): *If the programmer mistakenly passes the value 0 in val, the "fake" return will instead return 1.* – Gerhardh Jun 29 '22 at 10:35

1 Answers1

5

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396