52

Is it possible to set values for default parameters in C? For example:

void display(int a, int b=10){
//do something
}

main(){
  display(1);
  display(1,2); // override default value
}

Visual Studio 2008, complaints that there is a syntax error in -void display(int a, int b=10). If this is not legal in C, whats the alternative? Please let me know. Thanks.

user1128265
  • 2,891
  • 10
  • 29
  • 34
  • 2
    Indeed it is not legal in C. C also doesn't have overloading. – Mysticial Feb 07 '12 at 23:09
  • 1
    Possible duplicate: http://stackoverflow.com/questions/1472138/c-default-arguments – Timothy Jones Feb 07 '12 at 23:11
  • http://stackoverflow.com/questions/2988038/default-values-on-arguments-in-c-functions-and-function-overloading-in-c –  Apr 23 '14 at 05:52
  • Possible duplicate of [Default values on arguments in C functions and function overloading in C](https://stackoverflow.com/questions/2988038/default-values-on-arguments-in-c-functions-and-function-overloading-in-c) – Jonathan Mee Apr 06 '18 at 13:53

5 Answers5

82

Default parameters is a C++ feature.

C has no default parameters.

ouah
  • 142,963
  • 15
  • 272
  • 331
21

It is not possible in standard C. One alternative is to encode the parameters into the function name, like e.g.

void display(int a){
    display_with_b(a, 10);
}

void display_with_b(int a, int b){
    //do something
}
Joni
  • 108,737
  • 14
  • 143
  • 193
  • 1
    +1. I also like the practice in a comment on [this answer](http://stackoverflow.com/a/1472310/790070), where the name of the function includes the number of parameters it takes. – Timothy Jones Feb 07 '12 at 23:15
10

There are no default parameters in C.

One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed. This is dangerous though so I wouldn't recommend it unless you really need default parameters.

Example

function ( char *path)
{
    FILE *outHandle;

    if (path==NULL){
        outHandle=fopen("DummyFile","w");
    }else
    {
        outHandle=fopen(path,"w");
    }

}
RussS
  • 16,476
  • 1
  • 34
  • 62
2

If you are using a compiler compatible with C++2a, then there is a preprocessor trick that you can use, as explained at https://stackoverflow.com/a/10841376/18166707

You can use this code snippet as an example:

#include <stdio.h>

#define ADD_THREE(a,b,...) add_three_nums(a, b, (0, ##__VA_ARGS__))

int add_three_nums( int a, int b, int c)
{
  return a + b + c;
}

void main( void )
{
  printf("%d\n", ADD_THREE(3, 5));
  printf("%d\n", ADD_THREE(4, 6, 8));
}
JonS
  • 621
  • 7
  • 25
1

Not that way...

You could use an int array or a varargs and fill in missing data within your function. You lose compile time checks though.

Dtyree
  • 330
  • 2
  • 5