Reputation: 177
I'm a beginner, so apologies if I overstep any rules. Here's my question.
I am using a GCC compiler on Codeblocks and there is something peculiar I noticed with a particular snippet of code. I'm hoping someone could shed some light on this.
int main()
{
Tree *t;
//some operations on the tree
traverse();// No parameter is passed here.
...
}
void traverse(Tree *t)
{
..
}
In the following code, the function traverse() executes correctly. My question is why? I'm not sure about this, but if a function is not declared, its default type becomes int. Now, the compiler not only suppressed an error at the time of compilation, it also correctly supplied the parameter 't' to the function traverse().
Is this because of an intelligent compiler design?
So in general: the question I have is - what behavior does the compiler default to if it encounters a method that has not yet been declared? And more importantly, how does it "know" which parameter I wanted to pass?
For all you know, I could have had three instance of "Tree *": t1, t2 and t3. Which one would the compiler pass then?
I tried looking around on Google, but have yet to locate a definitive source.
Upvotes: 1
Views: 566
Reputation: 60721
The function is looking for its argument on the stack. The function doesn't know that the argument it's expecting isn't actually there.
By chance, the thing on the stack where it's looking for the argument is the local variable t
in your main()
function. If you had more local variables inside main()
, then one of them would be misinterpreted as the function's argument, and things would go badly wrong.
So, it's working purely by chance.
Upvotes: 3