Another C vs C++ "why is doing this thing?" : Forward Declarations
1 year, 5 months ago Edited by on July 13, 2016, 12:07 p.m. Reason: my english sucks
So I got this code, and I forgot to forward declare a function but I got it compiled anyway, I can't just figure it out why! Of course if I compile in c++ I got the expected error: C3861: identifier not found.
It' 6.4 exercise on the K&R book (really exited about using a binary tree and malloc for the fist time *_* even if I used virtual alloc following hmh, I feel more by myself using only a book :) )
Here's the code HAVE FUN @[email protected] :
by the way I'm using the microsoft compiler. Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64
P.S I also needed to include the malloc.h file which is not included in the original code, otherwise I got this warnings:
w:\ansic\code\ansic.c(91): warning C4312: 'type cast': conversion from 'int' to 'tNode *' of greater size 95 on this page
w:\ansic\code\ansic.c(99): warning C4312: 'type cast': conversion from 'int' to 'char *' of greater size 103 on this page
So if anyone know what's going on...
Another C vs C++
1 year, 5 months ago Edited by on July 13, 2016, 2:43 p.m.
If a function is not declared before use then the compiler assumes it is declared with an int return type and vararg paramters.
Why it doesn't error when it sees a definition of that function not matching that assumption I'm not clear about.
Another C vs C++
1 year, 4 months ago
The C compiler doesn't do any typechecking on function calls without a declaration. The compiler assumes you know what you are doing. (If you have your warning level set high enough, it *will* warn on this. It's a good idea to do so.)
The reason this *works*, in this case, is that you're returning int, which is the assumed return type of an undeclared function. The only implication on the caller's side is how much stack to allocate for the return value. You call with the correct arguments, so they are passed properly.
Remember that "functions" are not really a machine level construct. A function call is a pointer to some other code, a place to stick the return value, and arguments placed on the stack / in registers according to a particular convention. So long as both sides of the call line up, it "Just Works". (But if you get it *wrong*, you smash the stack and your program dies. So you still want to use forward declarations.)