Reputation:
I have understood the difference between declaration and definition And I was practicing some question when I hit the doubt, the below code asked me to list out the error in the snippet.
f(int a,int b)
{
int a;
a=20;
return a;
}
Why does this gives re-declaration error of a
?
Shouldn't it give multiple definition of a
because in:
f(int a,int b)
— here a
is defined right?int a
is defined again?So why not multiple definition error?
Upvotes: 8
Views: 31521
Reputation: 23
When you declare a variable in your code,a block of memory will be allocated with that variable name depending on the data type used in your declaration.
But when you try to redeclare the same variable the processor tries to allocate the memory which is already allocated with the same name.so as the processor face ambiguity while trying to access the memory block with that variable name the compiler do not allow that instruction, hence multiple declarations will not be allowed and you will get a error in GCC compiler telling,
line 3 col 10 [Error]redeclaration of 'int a'
line 1 col 7 [Error]'int a' previously declared here
in your code
f(int a,int b) //first declaration of 'a'
{
int a; //redeclaration of 'a', whose memory is already allocated
a=20;
return a;
}
on the memory layout two blocks cannot have same identity(variable name), hence the compiler throws a redeclaration error as multiple declarations are not possible, when variable 'a' is redeclared.
Upvotes: 1
Reputation:
A definition is always a declaration. The difference is that a definition also gives whatever you declare some value.
In your example, by the way, it is only a redeclaration error:
f(int a, /* Defines a */
int b)
{
int a; /* Declares a - error! */
a=20; /* initializes a */
return a;
}
You probably meant to do this:
f(int a, /* Defines a */
int b)
{
int a = 20; /* Declares and defines a - error! */
return a;
}
But in this case, most compilers will throw a "redeclaration" error too. For example, GCC throws the following error:
Error: 'a' redeclared as a different kind of symbol
That is because a
is originally defined as a parameter, which is different from a variable definition inside the function's scope. As the compiler sees that you're re-declaring something that is of a different "breed" than your new declaration, it can't care less if your illegal declaration is a definition or not, because it regards "definition" differently in terms of function parameters and function local variables.
However, if you do this:
int c = 20;
int c = 20;
GCC, for example, throws a redefinition error, because both c
-s are the function's local variables.
Upvotes: 9