cmingw

MinGW compiler doesn't need function declarations?


I have these two files:

// first.c
int main(void) {
  putint(3);
}

and

// second.c
#include <stdio.h>
void putint(int n) {
  printf("%d",n);
  getchar();
}

When I run gcc 4.6.1 under Win XP:

gcc first.c second.c -o program.exe

It has no problem and writes 3 to stdout. It doesn't need putint declaration in first.c. How is this possible? Is this standard behavior?

I have tested this on MSVC 2008 Express and it runs only with the declaration as expected.

// first.c
void putint(int);
int main(void) {
  putint(3);
}

Solved, thanks for hints, these options helped to show the warning:


Solution

  • This is a legacy "feature" of C that should not be used as of several decades ago. You should use a compiler with settings that will warn you if you do something like this. Gcc has several switches that you should specify when using it & one of them will give you a warning for this.

    Edit: I haven't been using gcc myself, but switches that you should check out are -pedantic, -Wall, -Wextra, and -std.

    The compiler that is accepting this is assuming, per the old language definition, that since you didn't see fit to tell it otherwise, the function a) returns an int value and b) since you pass it an int (or if you passed it something that could be promoted to an int) the function expects that argument to be an int.

    As @veer correctly points out, this should generally work in your particular case. In other cases, however, differences between the implicit assumptions for a function without a prototype and the function's actual signature would make things go boom.