简体   繁体   中英

when is memory allocated for value types in c#?

static void Main()
{
    int i;
    int j;
    j=10;
    i=2;
}

Is the memory allocated in stack for variables in the order in which their declaration appears or will it be allocated as they are initialized?

I think variables are loaded onto stack in the order in which they are declared while peers argue otherwise. So, according to them j is pushed onto stack first while i argue that i is pushed to stack first. who is correct?

The short answer is that you can not know the exact order of stack allocations.

Operations may be reordered by both the compiler and the processor for optimization purposes. And as Ehsan already pointed out in a comment, your code might not even be executed at all when a release build is used.

Have a look at this article The C# Memory Model , it may help explain why the exact order of allocation is not really something you can know beforehand.

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