Question

I just debugged a C program for a long time, only to find that I missed an argument when making a function call, so junk instead filled the missing argument. Stupid mistakes like this are really frustrating, but I suppose compilers should be able to detect this. (C doesn't even support default arguments; even in C++, default arguments need to be explicitly declared.)

Update: The prototype was found to be wrong, too...

So, is there a GCC flag for warning unmatched function call argument number? I always have -Wall and -pedantic on; it's quite surprising that such an obvious error goes undetected. (Actually I suppose there is some reason that GCC does not report, but I can't think of any at this time.)

Embarrassing code example:

    static void dfs();

    int main(int argc, const char *argv[]) {
         dfs(1);
    }

    static void
    dfs(int remain, int last) {
        // dfs
    }

Another discovery I just made is that if the prototype contains argument, the compiler will report; but the prototype happened to contains no arguments, then the compiler just slipped.

Was it helpful?

Solution

Unmatched number of function call arguments is a mandatory diagnostic that all compilers will and must provide without any special setting. It is mandated by the standard.

C99Standard 6.5.2.2 Function calls:
Constraints

If the expression that denotes the called function has a type that includes a prototype, the number of arguments shall agree with the number of parameters. Each argument shall have a type such that its value may be assigned to an object with the unqualified version of the type of its corresponding parameter.


 static void dfs();

Tells the compiler dfs is a static function which returns a void and can take unspecified number of arguments. Further you provide a definition for the function which takes 2 arguments & call the same. As you see there is no breaking of contract. The problem is the declaration of the function is incorrect. If you want to declare a function which takes no arguments you must use:

 static void dfs(void);

Once you do that the compiler will provide you a diagnostic.

OTHER TIPS

There are various options you can use:

  • -Wstrict-prototypes
  • -Wmissing-prototypes
  • -Wold-style-definition
  • -Wold-style-declaration

These work even if you're not using -std=c99 or something similar. I'm plagued by antique code at the office and use these (except -Wstrict-prototypes) when I'm cleaning up some code that hasn't been given 'the treatment'. The exception is because the pointers to functions in the code base are mostly without the necessary argument lists. For personal code, or code I'm in charge of, this isn't a problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top