PSkocik PSkocik - 13 days ago 5
C Question

Why don't my local function declarations work if the function is static?

I tried to do the equivalent of:

enum en{
en_a,
en_b,
en_c,
en_d,
};
struct node{ enum en tag; };


#define CASE(x) case en_##x:; \
static int x(struct node*); \
return x(n);

int run(struct node* n)
{
switch(n->tag){
CASE(a);
CASE(b);
CASE(c);
CASE(d);
}
abort();
}
static int a(struct node* n){
return 0;
}
static int b(struct node* n){
return 0;
}
static int c(struct node* n){
return 0;
}
static int d(struct node* n){
return 0;
}


Basically tag dispatch into static functions.

I wanted the
switch
to be at the very top of my file for better readability (I have more enumerations than 4) so I tried to fit the static function declarations into the
switch
block along with the rest of the
CASE
boilerplate.

This works fine if I delete (
#define static /*empty*/
) all the static keywords, but with the statics it breaks with:
error: static declaration of ‘a’ follows non-static declaration
(gcc).

What's the reason for this behavior?

usr usr
Answer

It's not valid (and doesn't make sense) to declare a function inside another with static keyword. C standard explicitly prohibits this:

C11 draft, 6.7.1:

The declaration of an identifier for a function that has block scope shall have no explicit storage-class specifier other than extern.

Comments