How to create a function with an optional parameter in C

3 Answers

0 votes
// C does not support optional parameters 
// But we can simulate optional parameters using a few classic C techniques.

// Optional Parameter Using NULL

#include <stdio.h>

void greet(const char *name) {
    if (name == NULL) {
        printf("Hello, Guest!\n");
    } else {
        printf("Hello, %s!\n", name);
    }
}

int main() {
    greet("Alpha");   
    greet(NULL);   
    
    return 0;
}


/*
run:

Hello, Alpha!
Hello, Guest!

*/


 



answered 2 hours ago by avibootz
0 votes
// C does not support optional parameters 
// But we can simulate optional parameters using a few classic C techniques.

// Optional Parameters Using Variadic Functions (...)

#include <stdio.h>
#include <stdarg.h>

void greet(int count, ...) {
    va_list args;
    va_start(args, count);

    if (count > 0) {
        const char *name = va_arg(args, const char *);
        printf("Hello, %s!\n", name);
    } else {
        printf("Hello, Guest!\n");
    }

    va_end(args);
}

int main() {
    greet(0);             
    greet(1, "Alpha");      
    
    return 0;
}



/*
run:

Hello, Guest!
Hello, Alpha!

*/


 



answered 1 hour ago by avibootz
0 votes
// C does not support optional parameters 
// But we can simulate optional parameters using a few classic C techniques.

// Optional Parameters Using a Struct

#include <stdio.h>
#include <string.h>

typedef struct {
    const char *name;
    int shout;
} GreetOptions;

void greet(GreetOptions opts) {
    const char *name = (opts.name == NULL) ? "Guest" : opts.name;

    if (opts.shout) {
        char buffer[100];
        int i = 0;
        while (name[i] && i < 99) {
            buffer[i] = (name[i] >= 'a' && name[i] <= 'z') ? name[i] - 32 : name[i];
            i++;
        }
        buffer[i] = '\0';
        printf("Hello, %s!\n", buffer);
    } else {
        printf("Hello, %s!\n", name);
    }
}

int main() {
    GreetOptions opts1 = { NULL, 0 };
    greet(opts1); 

    GreetOptions opts2 = { "Alpha", 0 };
    greet(opts2); 

    GreetOptions opts3 = { "Proxima", 1 };
    greet(opts3); 

    return 0;
}



/*
run:

Hello, Guest!
Hello, Alpha!
Hello, PROXIMA!

*/


 



answered 1 hour ago by avibootz
...