Home > Blockchain >  program compiled when function parameter does not match the const parameter declaration in c
program compiled when function parameter does not match the const parameter declaration in c

Time:12-16

I have a piece of code like this:

#include <stdio.h>

int add(const int x, const int y);

int main()
{
    printf("%d", add(9, 8));

    return 0;
}

int add(int x, int y)
{
    return x   y;
}

I forward declared the function "add" with const parameters after that i defined it without the const parameter, and when i compile it the compiler gives no complain.
The out put of the program is: 17. Why does this happen ?

CodePudding user response:

Well, the function declaration and function definition have to be compatible, we all know that. So the same name and same return type and type of parameters. So we know from C11 6.7.6.3p15:

For two function types to be compatible, [...] corresponding parameters shall have compatible types. [...]

But, there is an explicit backdoor, later in that text:

(In the determination of type compatibility [...] each parameter declared with qualified type is taken as having the unqualified version of its declared type.)

The type-qualifier is for example const. And it is ignored. You can put any type-qualifier and it is just ignored when checking if the function declarations are the same with each other.

int func(int n);
int func(volatile int n);
int func(const int n);
int func(const volatile int n);
int func(int n) {
    return n;
}
  • Related