Default and optional arguments

How can I use default arguments and optional arguments in c. I tried to create using struct and define. how does functions like open work with optional arguments.Another doubt about pointer
whats difference between these two.

int i ,*ip;
i = 9;
ip = i;
ip = &i;

C doesn’t really support default and optional arguments.

I think the only way to do default values is to allow arguments to be NULL or 0 and set them to the default value in that case.

Optional boolean arguments are possible with bit flags. You can accept a parameter that is the bitwise OR of a number of defined integer constants. Based on the integer you get you can calculate which “flags” you got.

1 Like

ip = &i would correctly assign the address of i to the pointer.

Like florian said C doesn’t have default arguments. Usually you’d use the ternary at the top of the function like this:

int run(int miles) {
   miles = miles < 0 ? 100 : miles;

That’s basically a one-liner for this:

int run(int miles) {
   if(miles < 0) {
        miles = 100;
   } else {
        miles = miles;

But if you did an If you could also do this:

if(miles < 0) miles = 100;

Now, personally I don’t like defaults in C because they’re too hard to get right. I prefer to set strict input settings and then use assert to bomb out if people violate them:

#include <assert.h>

int run(int miles) {
   assert(miles >= 0 && "You must give a positive integer for miles to run.");

I find this is superior in many ways, but if you use the assert(test && "msg") trick then not only do you get the assertion test to find bugs but you also get a handy error message to help you figure out why it was an error.

1 Like