Why can't I specify the storage class for formal parameters of a function?
Asked Answered
B

1

9

When I do as below the code works fine :

#include <stdio.h>
void test( int a)
{
 printf("a=%d\n",a);   
}

int main()
{
    test(10);
    return 1;
}

But when I do

#include <stdio.h>
void test( auto int a) // Or static int a Or extern int a
{
 printf("a=%d\n",a);   
}

int main()
{
    test(10);
    return 1;
}

It generates an error,

error: storage class specified for parameter 'a'

Why is that error? What happens internally(memory management)?

But it works fine without any error when I do:

void test( register int a)
{
 printf("a=%d\n",a);   
}

Why is that?

Brotherton answered 8/6, 2017 at 14:53 Comment(1)
How could a parameter be static? It would change with every call to the function anyway... And it definitely can't be externBrewster
P
15

First,quoting C11, chapter 6.7.6.3

The only storage-class specifier that shall occur in a parameter declaration is register.

So, this is explicitly specified in the standard.

That said, this restriction exists because with an explicit storage class like static/ extern, there will be problems in memory management, as function parameters are in the block scope for the function and their lifetimes are limited to the execution of the function body.

  • A parameter variable cannot outlive the call to the function; otherwise, what would be the effect of the argument in the next call to the same function? So static storage is not meaningful, and auto is redundant.

  • Since the function parameters has no linkage, extern also makes no sense.


Additionally, as mentioned in C11, for a hosted environment, the conforming signature for main() is int main(void), at least.

Polemic answered 8/6, 2017 at 14:57 Comment(3)
OK, I took advantage of your invitation. Hope it's ok with you.Becht
@Becht More than okay sir, thanks for the contribution, as always. :)Polemic
Very nice answer, with explaining the rationale.:-)Boyhood

© 2022 - 2024 — McMap. All rights reserved.