Is “int a;” a declaration or definition in C and in C++?

不羁岁月 提交于 2019-11-29 19:00:20

问题


Is int a; a declaration or definition in C? Is there any difference in C++?

I was always thinking it's just a declaration, until today...

Is it a declaration or a definition?


回答1:


A declaration describes an object, whereas a definition requests the creation of an object. All definitions are also declarations, but the reverse is not true.

In the case of int a;, what it is depends on where it is placed in the source code:

  • Within a function, int a; is a definition - it requests the creation of an int variable with automatic storage duration (and of course also a declaration);
  • At file scope, the answer is different in C and C++. In C, int a; is a tentative definition (of which there can be more than one, as long as the types and linkage are agreeable); in C++, it is an ordinary definition with external linkage.
  • Within a struct or union specifier, int a; is a declaration of a member.



回答2:


Where does it appear in your program?

In most contexts, it is both a declaration and definition.

OTOH, extern int a; is a declaration only.




回答3:


Consider:

int a;

It's a definition as well as a declaration.

Consider the following example...

int i;
printf("%d", i);

Some junk value will be printed. Which obviously means it's got a memory location.

If you want to just declare a variable and not define it then go for "extern" keyword.

Thus extern int b; is just a declaration and not a definition.

Example:

extern int var;
int main(void)
{
    var = 10;
    return 0;
}

Thus the above program will throw an error as "var" was not defined anywhere.



来源:https://stackoverflow.com/questions/4476169/is-int-a-a-declaration-or-definition-in-c-and-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!