Not So Stupid C/C99 Tricks

URL's are Valid Syntax

URLs are valid C syntax:<BR>
Label    Comment

Simulating C++11's static if in C

Negative array indexes in a declaration cause a compile error. With a macro which evaluates a true/false condition.
/* Force a compilation error if condition is true */
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
// So, in your code, if you have some structure which must be, say a multiple of 8 bytes in size, maybe because of some hardware constraints, you can do:
BUILD_BUG_ON((sizeof(struct mystruct) % 8) != 0);

Replace Macros With Inline Functions

Consider a macro:
#define BLAH(x,y) \
    do { \
         int i; \
         for (i=0; i<y; ++i) \
             ++x; \
    } while(0)
Now most coders would think this would expand to the most efficient code possible -- so what if its opaque? In C99 this is pretty much the same thing:
static void inline blah(int x, int y)
    int i;
         for (i=0; i<y; ++i) 

"Goes to" Operator (DONT DO THIS)

In a while or for conditional, one can write cryptic code which reads "while i goes to 0, do ...".
int i;
    i = 10;
    while(i --> 0) { ... }

Releasing Resources Upon Thread Exit/Cancellation

Use pthread_cleanup_push() and pthread_cleanup_pop or pthread_key_create(). Remember that the _push() and _pop() calls are really macros, and must be balanced in the same lexical scope. The pthread_key_create()/pthread_setspecific() is somewhat more flexible, but it also has some quirks -- the calls to destructor functions is not ordered.

Semaphores and Thread-pinning

Details, details. For performance, often a thread is restricted or 'pinned' to a specific processor. Sometimes pinned threads are set to different physical cores. Semaphores protecting data should be aligned to be on a different cache boundry than the data itself. (Due to frequent cache invalidation of semaphores.)

-- JoeBrandt - 2013-05-08
Topic revision: r3 - 2013-05-10, JoeBrandt
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding NRAO Public Wiki? Send feedback