Inconsistent declaration and definition in C

Today I spent a lot of time looking for the "error" that can be demonstrated with this simple code:

main.c

#include "func.h"
#include <stdio.h>
void main(){printf("func: %f", getX());}

      

func.c

#include "func.h"
static float x[2] = {1.0f, 2.0f};
float getX(int n){return x[n];}

      

func.h

float getX();

      

and it compiles and links (VS2010 with / W 3) without any warning . Sample output from a run

func: 1.000000

      

Can someone explain to me how this might work if the function declaration and definition are not the same and why shouldn't you issue any warnings?

thank

+3


source to share


2 answers


In C:

float getX();

      

is not the same as:

float getX(void);

      

In the first case, you specify a function that returns float

but takes undefined parameters - in the second case, you specify a function that returns float

but that does not take any parameters.



So the form definition is float getX(int n)

compatible with the first case, but not the second, which explains why you don't see the error / warning.

If you go to the correct prototype (second version), you should see the required error / warning.

Note that this is different behavior than for C ++, where the two forms are equivalent.

As for the output you see when you run the program, this is just an accidental consequence of undefined behavior - literally anything can happen if you call a function with the wrong parameters.

Take the homemade post: In C, you should always use the second form when declaring a prototype that takes no parameters - unfortunately, you'll find that very often people miss out on it void

(probably due to bad habits gained from writing C ++ code or simply because it requires fewer keystrokes).

+4


source


This declaration means that getX takes any number of parameters:

float getX();

      



To declare a function that takes no parameters, use:

float getX(void);  // This will result in a compiler error for func.c

      

+4


source







All Articles