0

Is it ok to leave the parameters unused? I'm trying to run the function like this:

void encoder();
void encoder(int argc, FILE* inputFP, FILE* outputFP);

Is there a need for a second function, one for dealing with stdio and one for dealing with files? When I try to run void encoder(int argc, FILE* inputFP, FILE* outputFP); without any arguments I get errors:

error: too few arguments to function ‘void encoder(int, FILE*, FILE*)’
         encoder();```
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Richard
  • 27
  • 6

2 Answers2

1

Is it ok to leave the parameters unused?

No, all arguments must be present and correct.

You should also be careful that you do not provide different prototypes for a function (or any symbol) within a given application.


If you really want to call it with no arguments, then the best approach is to have two functions and call the one you're after:

void encoder(void) {
    encoder2(0, stdin, stdout);
}

void encoder2(int argc, FILE* inputFP, FILE* outputFP) {
    /* ... */
}

If you want to have a variable number of arguments, then you could look at using the macros in stdarg.h (like printf() and friends), though you still won't be able to get away with zero arguments, and you'll need to be very careful with your usage.

Attie
  • 6,690
  • 2
  • 24
  • 34
  • ..though you can have a convention that any argument that is not provided will be `NULL` or `0`. – Paul Ogilvie Nov 05 '19 at 14:34
  • Oh? Could you expand on that? – Attie Nov 05 '19 at 14:36
  • For example `encoder2(0,0,0)` means no arguments, use defaults `stdin` and `stdout`. – Paul Ogilvie Nov 05 '19 at 15:30
  • Oh I see, thanks... I thought you were implying that `encoder2(,,)` or similar would behave as `encoder2(0,0,0)`...(!) – Attie Nov 05 '19 at 16:02
  • Is it considered a good practice to allways pass void as an argument whenever you are going to run encoder() ? Or is it something that should be done in .h? – Richard Nov 05 '19 at 22:05
  • the prototype (`void encoder(void);`) is different to calling the function (`encoder();`). When declaring, the `void` is a _very good idea_, when calling you should not pass any arguments. – Attie Nov 06 '19 at 11:24
1

As you've discovered, no it's not valid.

C lacks the support for default values, so the arguments would be quite useless. The solution to this particular problem is to use magic FILE * "files" that map to the standard input/output channels, i.e. stdin and stdout from <stdio.h>.

unwind
  • 391,730
  • 64
  • 469
  • 606