Converting a C++ lib to ANSI C and it seems like though ANSI C doesn\'t support default values for function variables or am I mistaken? What I want is something like
No, Standard C does not support either. Why do you feel you need to convert your C++ code to C? That could get quite tricky - I'd have thought writing wrappers would be the way to go, if your C++ must be callable from C.
i think u can use a function with variable arguments here is my example
#include <stdarg.h>
#include <stdio.h>
void baz( int flag, ... )
{
va_list ap;
char *bar = "baz"; /* default value */
va_start( ap, flag );
if ( flag == 1 )
bar = va_arg( ap, char * );
va_end( ap );
printf( "%s\n", bar );
}
int main( void )
{
baz( 0 );
baz( 1, "foo");
baz( 2 );
baz( 1, "bar");
return 0;
}
the output is
baz
foo
baz
bar
if u look for example man 2 open they say
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
int openat(int dirfd, const char *pathname, int flags);
int openat(int dirfd, const char *pathname, int flags, mode_t mode);
but mode is actually a ... argument
There is a way to support as many default parameters you need, just use a structure.
// Populate structure with var list and set any default values
struct FooVars {
int int_Var1 = 1; // One is the default value
char char_Command[2] = {"+"};
float float_Var2 = 10.5;
};
struct FooVars MainStruct;
//...
// Switch out any values needed, leave the rest alone
MainStruct.float_Var2 = 22.8;
Myfunc(MainStruct); // Call the function which at this point will add 1 to 22.8.
//...
void Myfunc( struct FooVars *MyFoo ) {
switch(MyFoo.char_Command) {
case '+':
printf("Result is %i %c %f.1 = %f\n" MyFoo.int_Var1, MyFoo.char_Command, MyFoo.float_Var2, (MyFoo.float_Var2 + MyFoo.int_Var1);
break;
case '*':
// Insert multiply here, you get the point...
break;
case '//':
// Insert divide here...
break;
}
}