I'm reading K&R and started wondering, why do variables need to be declared before they are used, but functions dont?
In C, all variables must be declared before they are used, usually at the beginning of the function before any executable statements.
Regarding functions it says:
The declaration
int power(int base, int n);just beforemainsays that power is a function that expects two int arguments and returns an int. This declaration, which is called a function prototype, has to agree with the definition and uses of power. It is an error if the definition of a function or any uses of it do not agree with its prototype
Does it have something to do with allocating memory for variables? e.g the compiler needs to know the variable size when it uses it, but couldnt it wait until it found the declaration?
The second (and last) edition of K&R is way out of date with respect to the current specifications of ISO C. The language it describes is aligned with C90. These days it has more historical value than technical value.
I don't see how the quotations you present support the idea that functions do not need to be declared before use, although that was in fact true in C90. It is not true in any of the versions of the C language since, however: C99, C11, C17, and (soon) C23 all require functions to be declared before use. Modern compilers may accept implicitly-declared functions for backward compatibility reasons, however.
Nevertheless,
Not really. A compiler could support automatic variables without advance declaration -- Fortran compilers did, for example, even before C was a twinkle in Dennis Ritchie's eye.
My best guess at the practical reason is that it makes C compilers easier to write and simpler (and smaller, which was important at the time). It may also be drawn in part from C's predecessor, B, though I'm having trouble determining whether B actually required pre-declaration (it did allow that).
With functions, on the other hand, a linking step was (and is) required whether functions are declared before use or not, so requiring declaration before use does not make compilers any easier, simpler, or smaller.
Nope. Implicit data typing was a known thing at the time of C's invention, and C had it. In early C, variable declarations did not need to specify a data type. It was sufficient to provide a storage-class specifier and name, in which case the type defaulted to
int. And again, Fortran did not require variable declaration before use, so we can conclude that it would have been feasible for C not to require it, either.