views:

141

answers:

1

What is the difference between the following two declarations:

 1. int foo(int); 
 2. int foo(int());

I am not sure if both the declarations are equivalent. What makes (2) different from (1)?

+15  A: 

int foo(int); is the declaration of a function taking an integer as an argument and returning an integer as well

int foo(int()); declares a function taking as an argument "a pointer to a function returning int and taking {no arguments[in C++] and unspecified number of arguments[in C]} " and returning an integer.

(2) is equivalent to int foo(int (*pf)()) and int foo(int f())

Prasoon Saurav
Taking no arguments? I believe you mean taking unspecified but not variadic arguments. `(void)` is the way to specify "no arguments".
R..
@R I belive that is C only, not C++
Tom
@R: Sorry I missed that. Added to my post.
Prasoon Saurav
I think you mean "`(2)` is equivalent to `int foo(int (*pf)())`..."
John Bode
@John Bode: Ohh! I need a cup of tea `:)`
Prasoon Saurav
To clarify, what @R means is that a specific invokation of `foo` can only call `pf` with a certain but unspecified numbre of arguments. But `foo` can take functions that accept different number of arguments in *different* invocations of `foo`. I.e I think this is valid: `void f(void a(), int i) { if (i == 0) a(); else a(1); } void g() { } void h(int i) { } int main() { f(g, 0); f(h, 1); }` but this is undefined behavior: `void j(int a()) { a(); a(1); }` as is this: `void j(int x, ...) { } int main() { f(j, 1); }`
Johannes Schaub - litb
@Johannes: That's roughly correct. What I mean is that the function pointed to cannot be a variadic function, but the pointer is able to point to a function with arbitrary argument types compatible with default promotions as long as the correct types corresponding to the actual function pointed to are used when making the call.
R..