假设我有一个声明和初始化两个局部变量的函数 - 默认情况下它具有存储持续时间auto.然后,该函数调用第二个函数,它传递这两个局部变量的地址.第二个功能可以安全地使用这些指针吗?
一个简单的程序化示例,以补充该描述:
#include <stdio.h>
int adder(int *a, int *b)
{
return *a + *b;
}
int main()
{
auto int a = 5; // `auto' is redundant; included for clarity
auto int b = 3;
// adder() gets the addresses of two auto variables! is this an issue?
int result = adder(&a, &b);
printf("5 + 3 = %d\n", result);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该程序按预期工作,打印5 + 3 = 8.
通常,当我对C有疑问时,我会转向标准,这也不例外.具体来说,我检查了ISO/IEC 9899,§6.2.4.它在那里说:
4声明标识符且没有链接且没有存储类说明符的对象
static具有 …