【发布时间】:2020-04-24 19:37:00
【问题描述】:
因此,AFAIK 您可以根据需要多次在 C 中声明一个名称,但您不能多次重新定义一个名称。同样根据我的想法,声明是在引入名称时。比如说,编译器会将该名称添加到符号表中。定义是为名称分配内存。现在,这里再次声明了名称 p。它没有被再次定义。
#include <iostream>
#include <cmath>
float goo(float x)
{
int p = 4;
extern int p;
cout << p << endl;
return floor(x) + ceil(x) / 2;
}
int p = 88;
但是,我收到以下错误:
iter.cpp: In function ‘float goo(float)’:
iter.cpp:53:16: error: redeclaration of ‘int p’
extern int p;
^
iter.cpp:52:9: note: previous declaration ‘int p’
int p = 4;
据我所知,int p = 4; 应该在调用堆栈上为 p 分配内存,即引入一个新的局部变量。然后, extern int p 应该再次声明 p。现在 p 应该引用全局变量 p 并且这个 p 应该在函数 goo 的所有后续语句中使用。
【问题讨论】:
标签: c++ compiler-errors scope global-variables forward-declaration