c - 为什么不能指定函数形参的存储类?

标签 c function formal-languages storage-class-specifier

当我执行以下代码时,代码工作正常:

#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/

相关文章:

c - 终端如何从标准输出读取并在屏幕上绘制文本?

sql - PgAdmin 函数返回类型

在 dplyr 0.7+ 函数中重命名

regex - 如何从正则表达式中找到语言?

java - 是否需要参数

我们可以减少 ESP IDF 锅炉板尺寸吗?

c - CodeBlocks(适用于 Windows)中的 sleep C 功能无法正常工作

c - 如何使用 bpf 返回数据包

c++ - 从字符串到函数的映射中存在语法错误

math - 这种语言与自身的串联是什么?