Armand Grillet
Armand Grillet

Reputation: 3399

longjmp(buffer, 0) doesn't return 0

I'm trying to do something simple using setjmp/longjmp: asking a user to press Enter many times and if the user inserts something else it will restarts the process using longjmp.

I'm using a counter to check if it works, this counter is 0 at start but when longjmp is used the counter restarts at 1.

#include <stdio.h>
#include <setjmp.h>
jmp_buf buffer;
char inputBuffer[512];

void handle_interrupt(int signal) {
    longjmp(buffer, 0);
}

int main(int argc, const char * argv[]) {
    int counter = 0;
    counter = setjmp(buffer); // Save the initial state.

    printf("Counter: %d\n", counter);

    printf("\nWelcome in the jump game, press enter (nothing else!): \n");
    while (fgets(inputBuffer, sizeof(inputBuffer), stdin)) {
        if (*inputBuffer == '\n') { // If user press Enter
            counter++;
            printf("%d\n\n", counter);
            printf("Again: \n");
        } else {
            handle_interrupt(0);
        }
    }
}

Output:

pc3:Assignement 3 ArmandG$ ./tictockforever
Counter: 0

Welcome in the jump game, press enter (nothing else!): 

1

Again: 

2

Again: 
StackOverflow
Counter: 1

Welcome in the jump game, press enter (nothing else!): 

2

Again: 

I know that this code is silly, I'm just trying to use setjmp/longjmp on a simple example.

Upvotes: 2

Views: 314

Answers (2)

gnasher729
gnasher729

Reputation: 52592

You need to download a copy of the C Standard (Google for "C11 Draft Standard" for example) and read the documentation of setjmp / longjmp very, very carefully. setjmp is not a function like others. Your use of setjmp is absolutely illegal. About the only legal way to use it is something like

if (setjmp (...)) {
    ...
} else {
    ...
}

Upvotes: 4

Deduplicator
Deduplicator

Reputation: 45674

setjmp only returns 0 when returning the first time, directly.

In any other cases, it returns whatever you passed to longjmp, unless you passed 0:
In that case it returns 1.

Upvotes: 6

Related Questions