When is stack space allocated for local variables?

前端 未结 5 2068
独厮守ぢ
独厮守ぢ 2021-01-02 02:54

I have a question about the following C code:

void my_function()
{
    int i1;
    int j1;

    // Do something...

    if (check_something())
    {
                 


        
相关标签:
5条回答
  • 2021-01-02 03:31

    The compiler is free to do whatever it wants, as long as the semantics of the language are reserved. In other words, i2 and j2 can be bound to memory places before the execution reaches the entry point of their block, and can be unbounded any time as long as that doesn't affect the semantics of your code.

    0 讨论(0)
  • 2021-01-02 03:33

    If the variables are going to be put on the stack, the stack space is allocated at the beginning of the function before the first statement in the function. The stack pointer will be moved up (or down) the total number of bytes to store all the local variables.

    0 讨论(0)
  • 2021-01-02 03:34

    As I understand you even can't receive any guarantee these variables are allocated on stack, they could be stored in registers.

    What you really could affect here:

    • Advice compiler to place variable to register by using register keyword.

    • Help compiler with localizing variable scope by moving declaration to as late place as you can:

        int f(void )  
        {
            /* var1 and var2 probably use the same place for storage. */
            {
                 int var1;
                 /* ... do something */
            }
    
            {
                 int var2;
                 /* ... do something */
            }
        }
    


    • Even given defined scope delay initialization:
    {
       int i; /* Yes, you must declare it at the begin of block.
    
       /* Do something... */
    
       i = START_VALUE;
       /* But you need it only here and below... */
    }
    
    0 讨论(0)
  • 2021-01-02 03:46

    There are no guarantees.

    Different optimization flags will likely result in different methods of saving variables.

    The compiler can even make 1 or more variables not use the stack at all and keep them in registers for the whole duration of the function execution.

    0 讨论(0)
  • 2021-01-02 03:57

    if "check_something()" is easily evaluated to 0, that whole block will be optimized out using a sufficiently high level of optimization. Yes, it's compiler-dependent. Generally, if you're checking the return value of a function call, it won't be optimized out. The best way to approach this would be to compiler it and actually look at the disassembly of the file to verify what you think is happening is actually happening.

    0 讨论(0)
提交回复
热议问题