简体   繁体   中英

Variable Declaration & Memory Allocation

I want to know whether memory is allocated during the local variable declaration process.

Suppose I write this code inside function, int a =10; memory is allocated and the value 10 is stored in that.

What about int a; ? This declaration statement will it allocate 4 bytes of memory?

Thanks.

When you call a method, space for each local variable is allocated on the stack.

So if you declare an int variable in a method, it's stack frame will take up an extra 4 bytes of memory.

No additional memory is used anywhere else, and it is cleaned up when the method returns.

Something important to understand here is that MSIL does not support declaring a property just anywhere in a method. Whenever you declare a variable in C#, the declaration is moved to the method header in the compiled bytecode. Every variable is allocated when the method is called.

Local variables are usually stored on stack, so indeed bytes are allocated for int :

int a;

Because it simply uses default value (0), so it is the same as:

int a = 0;

int is a value type, so on stack is stored its value. If you would create local variable with reference type:

SomeClass a;

Then on stack it would be allocated only reference (with value null, as it is default value for reference types). For more information you can refer this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM