Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does a c compiler do when doesn't find the matching function

Tags:

c

function

c99

Consider the following code:

#include<stdio.h>
int f()
{
        printf(" hey ");
        return 5;
}
int main()
{
        printf("hello there %d",f(4,5));
        f(4,5);
        return 0;
}

I expected something like too many arguments to function ‘int f()’ but it gives an output even in strict C99 compilation. why is this behavior? But it seems like a C++ compiler gives an error.

like image 709
sasidhar Avatar asked Dec 27 '22 13:12

sasidhar


2 Answers

C is much less strict than C++ in some regards.

A function signature f() in C++ means a function without arguments, and a conforming compiler must enforce this. In C, by contrast, the behaviour is unspecified and compilers are not required to diagnose if a function is called with arguments even though it was defined without parameters. In practice, modern compilers should at least warn about the invalid usage.

Furthermore, in function prototype declarations (without definition) in C, empty parentheses mean that the parameters are unspecified. It can subsequently be defined with any number of arguments.

To prevent this, use the following prototypeISO/IEC 9899 6.7.6.3/10:

int f(void)
like image 132
Konrad Rudolph Avatar answered Apr 27 '23 00:04

Konrad Rudolph


In addition to what Konrad wrote, C will also implicitly declare functions for you. For example:

int main(int argc, char** argv)
{
  int* p = malloc(sizeof(int));
  return 0;
}

will compile (maybe with a warning) without a #include <stdlib.h> that contains the declaration.

like image 39
sashang Avatar answered Apr 27 '23 01:04

sashang