function attribute returns_twice

2.7k Views Asked by At

I just was looking up funciton attributes for gcc (http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html) and came across the returns_twice attribute.

And I am absolutely clueless in what case a function can return twice... I looked up quickly the mentioned vfork() and setjmp() but continue without an idea how an applicable scenario looks like - anyone of you used it or can explain a bit?

2

There are 2 best solutions below

0
On BEST ANSWER

The setjmp function is analogous to creating a label (in the goto sense), as such you will first return from setjmp when you set the label, and then each time that you actually jump to it.

If it seems weird, rest assured, you should not be using setjmp in your daily programming. Or actually... you should probably not be using it at all. It is a very low-level command that break the expected execution flow (much like goto) and, especially in C++, most of the invariants you could expect.

0
On

When you call setjmp, it establishes that as a return point, then execution continues at the code immediately following the setjmp call.

At some point later in the code, calling longjmp (with the jump buffer initialized by the previous call to setjmp) returns execution to start from that same point again (i.e., the code immediately following the call the setjmp).

Therefore, the original call returns normally, then at arbitrary later times, execution returns (or at least may return) to the same point again.

The attribute simply warns the compiler of that fact.