When is memory space allocated to a variable?

The compiler allocates 4 bytes of memory when declaring a variable:

int a;

Or he allocates memory when he is assigned a value:

a = 5;

When is the memory allocated? During variable declaration or initialization?

+4
source share
3 answers

A variable is allocated when the structure containing it is placed.

For a local variable in a method, this (with some caveats) when calling the method.

For a static variable, this is when the class is "initialized" (which occurs some time after its loading and before its first use).

For an instance variable, this is when the instance is created.

+6
source

, . , , , , .

...

C, , , , . , () , . , .

C- . , , , . , :

int foo(int x) {
  int y = 5;
  if (x > 5)
    y += x;
  return y;
}

, - 5 y, - :

int foo(int x) {
  if (x > 5)
    return 5 + x;
  return 5;
}

y .

TL; DR - . , () .

+2

When we have a “ declared ” variable, we mean that we told the compiler about this variable, that is, its type and its name, and also allocated a memory cell for the variable (locally or globally). The last action of the compiler, memory allocation, is more correctly called the definition of a variable.

Just Definition = Variable declaration + Variable initialization

0
source

All Articles