Should the declaration in the future be identical to its partner in the definition?

Please note that in this code double quadratic (); at the top does not match double quadratic (double a, double b, double c) in the definition below main.

Oddly enough, this compiles! I use gcc -ansi -Wall -pedantic weird.c and no matter what flags I use, it works anyway.

This is contrary to what I was taught. Why does this compile and work correctly?

#include <stdio.h> #include <math.h> double inputValues(); double quadratic(); int main() { inputValues(); inputValues(); inputValues(); return 0; } double inputValues() { double a, b, c,derp; printf("Enter a value a: "); scanf("%lf", &a); printf("Enter a value b: "); scanf("%lf", &b); printf("Enter a value c: "); scanf("%lf", &c); derp = quadratic(a, b, c); printf("One x-value for this equation is %0.3f: \n", derp); return 0; } double quadratic(double a, double b, double c) { double quad; quad = (-b + sqrt(b*b-4*a*c))/(2*a); return quad; } 
+4
source share
4 answers

double quadratic();

declares a function that returns double with an indefinite (but fixed) number of parameters.

It matches the prototype of your function:

 double quadratic(double a, double b, double c) { /* ... */ } 

This is not equivalent:

double quadratic(void);

which is a prototype declaration of a function that returns double without a parameter.

+3
source

If you omit the parameter list, the compiler assumes that the function exists, but do not check that the parameters match.

Your code will not compile if you declared double quadratic(void); because their signatures will be complete and will not match.

Standard C, draft Committee - April 12, 2011, Β§6.7.6.3.15

For two types of functions that must be compatible, both must indicate compatible return types. Moreover, a list of parameters is listed if both of this agreement are consistent with the number of parameters and the use of the ellipsis terminator; appropriate parameters must be compatible types. If one type has a list of parameter types, and another type specified by the function declarator, which is not part of the definition function and contains an empty list of identifiers, the parameter list should not have an ellipsis terminator and the type of each parameter should be compatible with the type that promotions apply to by default.

+2
source

Initially, there were no prototypes in C; there were just function declarations, and these declarations did not include a parameter list. Later, when prototypes were added, the old declaration form had to be retained for backward compatibility.

+1
source

In C, an empty argument list in a function declaration means that the function accepts an undefined number of parameters. This is why the C compiler does not complain. The same code will be a mistake in C ++, because an empty list of parameters in the declaration means that the function takes no arguments.

+1
source

All Articles