Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 it to i, and i = 3 assigns 3 to that storage. But because of goto, definition is bypassed which means there is no storage allocated for i.

I heard that local variables are allocated either at the entry of the function (f() in this case) where they reside, or at the point of definition.

But either way, how can i be used while it hasn't been defined yet (no storage at all)? Where does the value three assigned to when executing i = 3?

void f()
{
    goto label;
    int i;

label:
    i = 3;
    cout << i << endl; //prints 3 successfully
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
148 views
Welcome To Ask or Share your Answers For Others

1 Answer

Long story short; goto will result is a runtime jump, variable definition/declaration will result in storage allocation, compile time.

The compiler will see and decide on how much storage to allocate for an int, it will also make so that this allocated storage will be set to 3 when "hitting" i = 3;.

That memory location will be there even if there is a goto at the start of your function, before the declaration/definition, just as in your example.


Very silly simile

If I place a log on the ground and my friend runs (with his eyes closed) and jumps over it, the log will still be there - even if he hasn't seen or felt it.

It's realistic to say that he could turn around (at a later time) and set it on fire, if he wanted to. His jump doesn't make the log magically disappear.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...