polslinux
polslinux

Reputation: 1779

how only some arguments to function C

I have this function:
void func(int a, int b, char s, FILE *fp, int flag)
and i want to use the function's args based on the flag. For example:
func(num, NOTHING, NOTHING, file, 1)
func(num, othernum, NOTHING, NOTHING, 2)
and on the function this_is_function i want to have:

void func(int a, int b, char s, FILE *fp, int flag){
if(flag == 1){
/* use a and file */
}
if(flag == 2){
/* use a,b */
}
/* etc etc */
}

i would like to know if it is possible and how to do this!
Thanks in advance :)

Upvotes: 0

Views: 142

Answers (4)

Indy9000
Indy9000

Reputation: 8861

Create seperate functions for each of the cases you are trying to handle. This would yield to more readable code. State your intention through your code rather than hack around it.

Upvotes: 2

ChaCha
ChaCha

Reputation: 77

Your code should work fine and moreover try it out once and check for any errors. I am sure as no error should occur. You can also try using switch case in the func with flag as the choice for switch. I am sure you are not going to use Nothing and othersum in your code.

Upvotes: 1

ouah
ouah

Reputation: 145859

You can pass 0 to int and char and NULL for pointers when you call the function and the arguments are not used.

func(num, 0, 0, file, 1)
func(num, othernum, 0, NULL, 2)

You can also use variadic functions. Variadic functions are functions with a variable number of arguments.

Upvotes: 2

unwind
unwind

Reputation: 399881

If by NOTHING you mean that you really want to omit that argument, I don't think it's possible the way you've outlined it.

The way this typically is done in C is through variable argument lists. That would mean you'd have to reformulate so that the flag goes first, since it decides the rest of the arguments:

void func(int flag, ...)
{
  va_list args;
  int num, othernum;
  FILE *file;

  va_start(args, flag);
  if(flag == 1)
  {
    num = va_arg(args, int);
    file = va_arg(args, FILE *);
  }
  else if(flag == 2)
  {
    num = va_arg(args, int);
    othernum = va_args(args, int);
  }
  va_end(args);

  /* Inspect `flag` again, and do things with the values we got. */
}

Then you can use the function like so:

func(1, 42, a_file);

or

func(2, 17, 4711);

This of course requires lots of care, since you're not getting a lot of help from the compiler anymore to match the values provided in the call to what the function expects.

I would recommend restructuring it into different top-level functions instead, that call a common "worker" function with the proper arguments:

func_mode1(42, a_file);
func_mode2(17, 4711);

these could then call func() with the proper flag value, filling in suitable defaults for arguments that don't apply (such as NULL for a non-used file pointer).

Upvotes: 4

Related Questions