-4

When we declare any global variable, for instance

int x;

it is equivalent to

extern int x; 

Now by default global variables are initialized to 0 by the compiler, which means they are allocated memory. But if I simply write

extern int x;

then this will only declare the variable, while no memory would be allocated to it. So, my query is that if I write extern before int x or I do not write it, in case of global variables, how is the compiler treating them differently? In the case where I simply write int x, it allocates memory and simultaneously it puts extern before int x, while in the case where I write extern int x, it only declares the variable while no memory is allocated to it. Please clarify how the compiler is behaving in both ways.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Radha Gogia
  • 765
  • 1
  • 11
  • 22

2 Answers2

7

The very premise of your question is incorrect. This

int x;

is a tentative definition (which will turn into a normal definition of x by the end of the translation unit).

This

extern int x; 

is a non-defining declaration, which is not a definition at all.

They are not even remotely equivalent.

A loose equivalent of your original definition would be

extern int x = 0;

This is a definition. But this is not an exact equivalent, since this definition is not tentative.

Keyword extern turns an object definition into a non-defining declaration if (and only if), there is no explicit initializer. If an explicit initializer is present, a definition remains a definition, even if you add extern to it.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

This can be answered by understanding external object definition and Tentative definition.

Quoting C11, chapter §6.9.2, (emphasis mine)

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    I wander why people still ignores the fact that the Standard should be read at least one time. – Michi Feb 21 '17 at 09:29
  • @Michi Agree. Many a times the standard text seems a bit tricky but upon careful study, that is the one authoritative source which can actually answer most of the questions. – Sourav Ghosh Feb 21 '17 at 09:39