So, AFAIK you can declare a name in C as many times as you want, but you cannot redefine a name more than once. Also according to what I think, a declaration is when a name is introduced. It is when, say, a compiler would add that name to the symbol table. A definition is when memory is allocated for a name. Now, here the name p is being declared again. It is not being defined again.
#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;
But, I get the following error:
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;
According to me, int p = 4;
should allocate memory for p on the call stack i.e. introduce a new local variable. Then, extern int p should declare p again. Now p should refer to the global variable p and this p should be used in all subsequent statements in the function goo.
you can declare a name in C as many times as you want, but you cannot redefine a name more than once.
This is false, or at least incomplete. If you have multiple declarations using the same name in the same scope, they must all declare the same thing. You cannot, for example, declare that p
is simultaneously both the name of a local variable and the name of an external variable.
If you want to use the same name for different things, the declarations must be in different scopes. For example
{
int p = 4;
{
extern int p;
extern int p; // Declare the same thing twice if you want.
std::cout << p << std::endl;
}
return floor(x) + ceil(x) / 2;
}
uses the name p
for two different variables, and uses different scopes to distinguish those meanings. So this is no longer an error. This is not advisable since it will confuse human programmers, but it is acceptable as far as the compiler is concerned.