Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enforce function signatures on a set of function declarations in C?

Tags:

c

I want to make sure that a set of functions have the same signature in some C code. Ideally I would be able to define a new type that described the return value and arguments of a function and then declare my set of functions using this new type.

Additionally, is there a way to specify default values for the arguments to this function typedef?

like image 226
quikchange Avatar asked Dec 14 '22 06:12

quikchange


1 Answers

/* define a typedef for function_t - functions that return void */
/*      and take an  int and char parameter */

typedef void function_t( int param1, char param2);

/* declare some functions that use that signature */

function_t foo;
function_t bar;

Now when you define the functions there will be an error if they do not use the same signature as in the typedef.

void foo( int x, char c)
{
    /* do some stuff */

    return;
}

/* this will result in a compiler error */
int bar( int x, char c)
{
    /* do some stuff */

    return 1;
}

As for your new question (added 20 Oct 08): "Additionally, is there a way to specify default values for the arguments to this function typedef?"

No, there's no way to add default parameters to the typedef. Certainly not in C, which doesn't support default parameters at all. Even in C++ you can't do this because the default value of a parameter is not part of the type. In fact, a class that overrides a virtual method from a base class can specify a different value for a default parameter (or even remove the default altogether) - however, this is something that should not be done in general as it will simply cause confusion (http://www.gotw.ca/gotw/005.htm).

If you're using C++ you might be able to get the behavior you want using one of (or a combination of) the following:

  • abstract base classes
  • overloading
  • template functions
  • macros

But it would be difficult to suggest something without knowing more specifics about exactly what you're trying to accomplish. And I think it's likely that the result might well be pretty hacky.

like image 167
Michael Burr Avatar answered May 19 '23 08:05

Michael Burr