当我执行以下代码时,代码工作正常:
#include <stdio.h>
void test( int a)
{
printf("a=%d\n",a);
}
int main()
{
test(10);
return 1;
}
但是当我这样做的时候
#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;
}
它会产生一个错误,
error: storage class specified for parameter 'a'
为什么会出现这个错误?内部发生了什么(内存管理)?
但是当我这样做时它工作正常没有任何错误:
void test( register int a)
{
printf("a=%d\n",a);
}
这是为什么?
最佳答案
首先,引用C11
,第6.7.6.3章
The only storage-class specifier that shall occur in a parameter declaration is
register
.
因此,这是明确在标准中规定的。
也就是说,这个限制的存在是因为像static
/extern
这样的显式存储类,在内存管理上会有问题,因为函数参数在 block 范围内对于函数及其生命周期仅限于函数体的执行。
参数变量的生命周期不能超过对函数的调用;否则,下一次调用同一个函数时参数的作用是什么?所以
static
存储没有意义,auto
是多余的。由于函数参数没有链接,
extern
也没有意义。
此外,如 C11
中所述,对于托管环境,main()
的一致签名是 int main(void)
,至少。
关于c - 为什么不能指定函数形参的存储类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44439073/