Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No defined type of a function parameter defaults to int? Am I insane?

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).

like image 792
Alexander Avatar asked May 04 '11 14:05

Alexander


2 Answers

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

like image 177
Erik Avatar answered Sep 29 '22 18:09

Erik


@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.

like image 33
Jerry Coffin Avatar answered Sep 29 '22 16:09

Jerry Coffin