Jens Gustedt's Blog

February 21, 2012

try, throw and catch clauses with P99

Filed under: C11, C99, language, P99, syntax — Jens Gustedt @ 21:59

Before C11 implementing try/throw/catch clauses with C alone was difficult. C lacked three features for that. First, there was no clear concept of threads. A throw that wants to unwind the stack to a calling function would have to capture the nearest try clause on the stack by inspecting a global variable. If you are running in a threaded environment (which most people do theses days) this global variable would have to hold the state of all current try clauses of all threads. With the new feature of _Thread_local variables (or their emulation through P99_DECLARE_THREAD_LOCAL in P99) this is now easy to solve. We just need a thread local variable that implements a stack of states.

The second feature that is useful for such an implementation are atomic operations. Though we can now implement a thread local variable for the stack of states, we still have to be careful that updates of that variable are not interrupted in the middle by signal handlers or alike. This can be handled with atomic operations, P99 also emulates the _Atomic feature on common platforms.

The third ingredient is _Noreturn. For C11 we can specify that a certain function will never return to the caller. This enables the compiler to emit more efficient code for if a branch in an execution ends with such an noreturn function.

These three interfaces together with other features that had been already present in P99, made it straight forward to implement P99_TRY, P99_THROW, P99_CATCH and P99_FINALLY.

(more…)

Advertisements

February 15, 2012

surprising occurrence of identifiers in header files

Filed under: C++, C11, C99, language, preprocessor — Jens Gustedt @ 17:35

I remember being stuck sometime ago because a system header at the time on the platform that I was using defined the undocumented identifier barrier. IIRC this even was a macro, which made the bug really hard to track, seemingly harmless code simply exploded.

Hopefully nowadays platform implementors are a bit more careful in not polluting the namespace, but still avoiding naming conflicts is not so easy. E.g inline functions are a useful tool when you want to expose small functions to all compilation units of a program. There is one pitfall, though, when it comes to naming conventions for their parameter names and local variables. If you get the name wrong, as in this simple example

inline double my_sin(double PHI) { return sinf(PHI); } 

other users of your code might encounter random problems if they define a macro PHI.
(more…)

Blog at WordPress.com.