STATUS

I just realized what variable hoisting is. And I feel like a noob for it taking this long.

Posts

Pages: 1
unity
You're magical to me.
12540
What is it? :D
What's variable hoisting? 'Hoisting' as in 'hoist the main sail'?
Arrr matey! This here var'ble be an integer, I say! Th' value be 6!
Variable hoisting is changing the scope of a variable's lifetime.

In ANSI C (aka, this code will work absolutely everywhere), you need to declare variables at the start of a scope. After the start of a scope, you have as many variable declarations as you want. But once you have even one thing that isn't a variable declaration, you can't have any more variable declarations in that scope.

/* ANSI C */
int someFunc(int x){
int y;
x = x*2;
/* I couldn't declare y here because there is a statement before it */
y = x;
return y;
}

The reason is that all variables are held on the stack, and weaker compilers had a super hard time with growing the stack in the middle a scope (that's kind of what scope is, an area where the stack is larger than before).

In modern days, this is fine:


/* C99 */
int someFunc(int x){
x = x*2;
/* Who cares? I didn't use it before I declared it. */
int y = x;
return y;
}

But the variable is 'hoisted' to the start of the scope. To the compiler, this is the same thing as the first function. This is because the compiler will need to grow the stack to hold the variable, and so it grows it at the start of the scope rather than in the middle.
In JavaScript (where I heard the term originally), it goes even further. When you declare something with 'var' (as opposed to the new term, 'let'), the variable is 'hoisted' to function scope. You can use it outside the scope you declared it in, as long as you use it in the same function, and after you declared it.

/* JavaScript */
function someFunc(){
{
var x = 23;
}
return x; // This is fine. x was hoisted out of its scope by 'var'.
}

I've written compilers and interpreters before. I feel silly for only figuring this out now :P
So... hoisting is (basically) the compiler "auto-sorting" the code so that declarations are performed first, before everything else? (Thus allowing function/method-wide use of said variable?)
Sort of. It's anytime the compiler changes 'where' a variable exists. Either by 'hoisting' it up to the start of the scope (as in C or C++, or really any compiled language), or 'hoisting' it out of the scope it was declared in (as in JavaScript).
Pages: 1