Passing a pointer to a function that doesn't match the requirements of the formal parameter

Posted by Andreas Grech on Stack Overflow See other posts from Stack Overflow or by Andreas Grech
Published on 2010-05-04T10:32:19Z Indexed on 2010/05/04 10:38 UTC
Read the original article Hit count: 217

int valid (int x, int y) {
    return x + y;
}

int invalid (int x) {
    return x;
}

int func (int *f (int, int), int x, int y) { 
    //f is a pointer to a function taking 2 ints and returning an int
    return f(x, y);
}

int main () {
    int val = func(valid, 1, 2),
        inval = func(invalid, 1, 2); // <- 'invalid' does not match the contract 

    printf("Valid:   %d\n", val);
    printf("Invalid: %d\n", inval);

    /*  Output:
     *  Valid:   3
     *  Invalid: 1
     */
}

At the line inval = func(invalid, 1, 2);, why am I not getting a compiler error? If func expects a pointer to a function taking 2 ints and I pass a pointer to a function that takes a single int, why isn't the compiler complaining?

Also, since this is happening, what happens to the second parameter y in the invalid function?

© Stack Overflow or respective owner

Related posts about c

    Related posts about pointers