问题描述
我了解声明和定义之间的区别当我遇到疑问时,我正在练习一些问题,以下代码要求我列出代码段中的错误.
I have understood the difference between declaration and definitionAnd 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;
}
为什么这会给出a
的重新声明错误?它不应该给出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)
—在这里a
定义正确吗? - 在函数正文中,是否再次定义了
int a
?
f(int a,int b)
— herea
is defined right?- and in the function body,
int a
is defined again?
那为什么不定义多个错误呢?
So why not multiple definition error?
推荐答案
定义始终是声明.区别在于,定义还可以为您声明的值提供任何价值.
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;
}
您可能打算这样做:
f(int a, /* Defines a */
int b)
{
int a = 20; /* Declares and defines a - error! */
return a;
}
但是在这种情况下,大多数编译器也会抛出重新声明"错误.例如,GCC会引发以下错误:
But in this case, most compilers will throw a "redeclaration" error too. For example, GCC throws the following error:
这是因为a
最初是作为参数定义的,与函数范围内的变量定义不同.正如编译器看到的那样,您正在重新声明与新声明具有不同品种"的东西,因此,无论您的非法声明是否为定义,它都不会在意,因为它在功能参数和功能局部变量方面对定义"的看法有所不同.
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.
但是,如果您这样做:
int c = 20;
int c = 20;
例如,
GCC 会引发 redefinition 错误,因为这两个c
-s都是函数的局部变量.
GCC, for example, throws a redefinition error, because both c
-s are the function's local variables.
这篇关于重新声明错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!