Hacker News new | ask | show | jobs
by Grishnakh 3820 days ago
Because it wastes memory and decreases performance, that's why.

If there's a section of code in your function that may or may not be executed, depending on a conditional, then allocating the memory for variables used within that code block will be a waste if you end up not executing it. Now, you could argue that that block should be turned into a separate function, but now you're doing another function call (unless it gets optimized out) which wastes performance, and you're making the code more cluttered if the code block is relatively small and not really worth turning into a separate function.

2 comments

Are not all the local variables allocated on the stack in the function prologue anyway? no matter where in the function they are defined. A typical function starts with subtracting the stackpointer to make space for the local variables if i'm not mistaken.
> allocating the memory for variables

Allocation of N variables on the stack is O(1) since it just moves the stack pointer by the total size of all variables.

You wrongly assume here that your C code will have to run on a stack machine.
Do you have a counterexample?