为什么不能为函数的形式参数指定存储类? [英] Why can't I specify the storage class for formal parameters of a function?

查看:270
本文介绍了为什么不能为函数的形式参数指定存储类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

但是当我这样做

#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;
}

它会产生一个错误,

错误:为参数"a"指定了存储类

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);   
}

那是为什么?

推荐答案

首先引用C11,第6.7.6.3章

First,quoting C11, chapter 6.7.6.3

在参数声明中出现的唯一存储类说明符是register.

因此,这是标准中明确指定的 .

So, this is explicitly specified in the standard.

也就是说,存在此限制是因为对于像static/extern这样的显式存储类,内存管理会出现问题,因为函数参数在该函数的块范围内,并且它们的生存期仅限于函数主体的执行.

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.

  • 参数变量不能超过对函数的调用;否则,下一次调用同一函数时,参数的作用是什么?因此static存储没有意义,而auto是多余的.

  • 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.

由于函数参数没有链接,因此extern也没有意义.

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

此外,如C11中所述,对于托管环境,main()的合格签名至少为int main(void).

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

这篇关于为什么不能为函数的形式参数指定存储类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆