Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 725
lex Avatar asked Dec 18 '10 01:12

lex


2 Answers

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.
like image 100
caf Avatar answered Oct 21 '22 11:10

caf


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.

like image 35
Ben Voigt Avatar answered Oct 21 '22 12:10

Ben Voigt