News for hackers. Stuff that matters.
Re:Some obscure C features by mort96 on Thursday January 25, 2018 @06:21PM (#16235707)
That's really neat, I hadn't considered that. I will definitely try it out, and might end up using it for the library.
Re:Some obscure C features by vpalanc1 on Friday January 26, 2018 @12:19AM (#16237188)
I think the other solutions proposed are better, but:

> Sadly, you can't set the value of an index in an array like that in the top level in C, only inside functions.

This is not exactly true. An assignment is a value, you can do e.g.

int a = b[x] = 0;

(which implies that you can do your array-index assignments at the global level by creating nonsensical/unused variables and initializing them).

Re:Some obscure C features by nialv7 on Thursday January 25, 2018 @07:11PM (#16235996)
There's a simple solution you're missing here:

__attribute__((constructor))

Re:Some obscure C features by kbob on Thursday January 25, 2018 @07:53PM (#16236204)
This is what I came to say. Here is a working example that builds an array of function pointers at program initialization time.

https://github.com/kbob/schetoo/blob/master/prim.h#L215

This also works across multiple source files, unlike __COUNTER__.

Re:Some obscure C features by mrgriffin on Thursday January 25, 2018 @06:38PM (#16235797)
Yeah, it's a weird one! I discovered the idea while building my own toy unit test library, but I never got around to finishing it.

The biggest downside is that (as far as I know) it's impossible to get this approach to coordinate across translation units, so you're forced to define a main in each test file (via the library's header file?). But I doubt that matters too much in practice.