For some odd reason I was copying an example in another language of which does not use types, and forgot to add one in to a function definition parameter, and it worked.
#include <stdio.h>
char toChar(n) {
//sizeof n is 4 on my 32 bit system
const char *alpha = "0123456789ABCDEF";
return alpha[n];
}
int main() {
putchar(toChar(15)); //i.e.
return 0;
}
I am sure that main defaults to int by most compilers of some standard (but only return), is this also a behaviour true for other functions as well or is this implementation defined? It seems just out of the ordinary, my compiler is just a slightly outdated GCC port (MinGW).
K&R-style function declaration:
void foo(n)
int n;
{
}
If type isn't specified, it defaults to int. This is valid in C89, not C99
@Erik's answer is correct, but (IMO) could be misunderstood rather easily.
What you have is a K&R style definition, that's entirely true. Since int
is considered the default type, if you have something like: foo(n) { }
, it means the return type and the type of n
are both int
by default.
C99 (mostly) removes the "default int" rule, but does not entirely remove K&R style definitions. That means the definition above is no longer allowed; to define foo
with the same types as above, you could still use:
int foo(n)
int n;
{
}
I.e., the K&R style definition is still allowed, but you do have to specify the return type and the parameter type, even if the type is int.
This style of function definition is, however, obsolescent (per §6.11.7). It's really only still allowed for the sake of ancient (pre-standard) code. You don't want to write new code this way, even though it's technically still allowed. For new code, you clearly want to use a prototype-style definition:
int foo(int n) {}
For those who care about such things, the K&R style definition is still used in some new code though. Its terser style can be useful (using the term loosely) in code-golf.
As long as we're at it: @stijn's answer is sort of correct as well. In particular when a function is defined this way (I.e., K&R style), all arguments are subject to default promotions. That means if you pass an integer type smaller than int
, it'll be promoted to int
before being passed, and if you pass a float
, it'll be promoted to double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With