Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring vs defining variables in c [duplicate]

As I know this is a declaration:

int i;

and this is a definition:

int i = 10;

May be I am wrong I don't argue.

The question is Does the compiler set aside memory for the declared (but not defined) variables?

like image 871
Radoslaw Krasimirow Avatar asked Nov 30 '25 12:11

Radoslaw Krasimirow


2 Answers

Definition is when storage is allocated for a variable. Declaration does not imply storage has been allocated yet.

A declaration is used in order to access functions or variables defined in different source files, or in a library. A mismatch between the definition type and the declaration type generates a compiler error.

Here are some examples of declarations that are not definitions, in C:

extern char example1;
extern int example2;
void example3(void);

From the C standard (n1256):

6.7 Declarations
...
5 A declaration specifies the interpretation and attributes of a set of identifiers.

A definition of an identifier is a declaration for that identifier that:
— for an object, causes storage to be reserved for that object;
— for a function, includes the function body;101)
— for an enumeration constant or typedef name, is the (only) declaration of the identifier.
like image 174
Sadique Avatar answered Dec 02 '25 04:12

Sadique


"Does the compiler set aside memory for the declared (but not defined) variables?"

No. Compiler only allocates memory for (at time of) variable definition, not on variable declaration.

You can better understand the logic using a simple analogy, multiple declaration is allowed for a single variable, but multiple definition is not.

like image 32
Sourav Ghosh Avatar answered Dec 02 '25 04:12

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!