How can a variable be used when its definition is bypassed?

后端 未结 8 1653
借酒劲吻你
借酒劲吻你 2020-12-09 02:11

In my mind, always, definition means storage allocation.

In the following code, int i allocates a 4-byte (typically) storage on program stack and bind

相关标签:
8条回答
  • 2020-12-09 02:40

    The position of the declaration of i is irrelevant to the compiler. You can prove this to yourself by compiling your code with int i before the goto and then after and comparing the generated assembly:

    g++ -S test_with_i_before_goto.cpp -o test1.asm
    g++ -S test_with_i_after_goto.cpp -o test2.asm
    diff -u test1.asm test2.asm
    

    The only difference in this case is the source file name (.file) reference.

    0 讨论(0)
  • 2020-12-09 02:47

    In my mind, always, definition means storage allocation.

    This is not correct. The storage for the variable is reserved by the compiler when it creates the stack-layout for the function. The goto just bypasses the initialization. Since you assign a value before printing, everything is fine.

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