Because in C, declaration and initialisation are deliberately different steps. They are deliberately different because that is how C is designed.
When you say this inside a function:
void demo(void)
{
int *param;
...
}
You are saying, "my dear C compiler, when you create the stack frame for this function, please remember to reserve sizeof(int*)
bytes for storing a pointer." The compiler does not ask what's going there - it assumes you're going to tell it soon. If you don't, maybe there's a better language for you ;)
Maybe it wouldn't be diabolically hard to generate some safe stack clearing code. But it'd have to be called on every function invocation, and I doubt that many C developers would appreciate the hit when they're just going to fill it themselves anyway. Incidentally, there's a lot you can do for performance if you're allowed to be flexible with the stack. For example, the compiler can make the optimisation where...
If your function1
calls another function2
and stores its return value, or maybe there are some parameters passed in to function2
that aren't changed inside function2
... we don't have to create extra space, do we? Just use the same part of the stack for both! Note that this is in direct conflict with the concept of initialising the stack before every use.
But in a wider sense, (and to my mind, more importantly) it's aligned with C's philosophy of not doing very much more than is absolutely necessary. And this applies whether you're working on a PDP11, a PIC32MX (what I use it for) or a Cray XT3. It's exactly why people might choose to use C instead of other languages.
- If I want to write a program with no trace of
malloc
and free
, I don't have to! No memory management is forced upon me!
- If I want to bit-pack and type-pun a data union, I can! (As long as I read my implementation's notes on standard adherence, of course.)
- If I know exactly what I'm doing with my stack frame, the compiler doesn't have to do anything else for me!
In short, when you ask the C compiler to jump, it doesn't ask how high. The resulting code probably won't even come back down again.
Since most people who choose to develop in C like it that way, it has enough inertia not to change. Your way might not be an inherently bad idea, it's just not really asked for by many other C developers.