Handmade Hero»Forums»Code
45 posts
setjmp/longjmp
Edited by NelsonMandella on Reason: Initial post
I'm looking for advice/opinions/wisdom on wether or not it makes sense to use the somewhat obscure C feature setjmp/longjmp in a commercial product. I currently use it to jump out of a failed assert and back to the beginning of the main loop where it then makes a graceful exit after displaying an error message.
Mārtiņš Možeiko
2559 posts / 2 projects
setjmp/longjmp
If it's performance sensitive code - don't use it. They are expensive operations. It it happens rarely (call to setjmp) or like once a frame, then it does not matter, use it.

Be careful if you put this functionality in API though. Because they do not play well with C++ code. They will skip calls to destructors when doing long-jmp.

If its just for showing error message and exiting, then what's wrong with function that will will print/display error and call ExitProcess (or whatever API is available for your platform)?
45 posts
setjmp/longjmp
It's a game, so yeah it's performance critical but setjmp is only called once a frame.

I assume you mean print the error through a windows alert box or something and not within the actual program itself. I just think that rendering the error message within the game itself is a lot more elegant and less jarring aesthetically than closing out the game window and bringing up a windows notification box with an annoying alert sound.
Mārtiņš Možeiko
2559 posts / 2 projects
setjmp/longjmp
You can do separate rendering loop in show-error-message function.
45 posts
setjmp/longjmp
Do you mean without ever returning to the main loop? Like creating a mini main loop complete with rendering within the show error message function?
Mārtiņš Možeiko
2559 posts / 2 projects
setjmp/longjmp
Yes, exactly.
511 posts
setjmp/longjmp
NelsonMandella
Do you mean without ever returning to the main loop? Like creating a mini main loop complete with rendering within the show error message function?


It's how some GUI libraries create "modal" dialogs, they enter a new loop and discard any user event that goes to the parent window.
45 posts
setjmp/longjmp
Very interesting. Is there any reason to favor this approach versus setjmp/longjmp (which seems to me simpler). And I assume this wouldn't work or would be much harder to pull off on OS X because of the timer callback stuff, as I also need to maintain a working mac build.
Mārtiņš Možeiko
2559 posts / 2 projects
setjmp/longjmp
Not many people know about setjmp/longjmp, its a bit obscure feature. Also it does not play well across API boundaries or different languages, like C++. longjmp will skip stack unwinding - that means there will be no destructors called.