How to set a default value to function parameters in C

1 Answer

0 votes
// In C, you can't directly set default values for function parameters. 
// However, you can achieve similar behavior by using wrapper functions.

#include <stdio.h>

void print(char *name, int times) {
    for (int i = 0; i < times; i++) {
        printf("The: %s.\n", name);
    }
}

// Wrapper function with a default value
void print_with_default(char *str) {
    print(str, 1);  // Default value for 'times' is 1
}

int main() {
    print_with_default("C Programming");  
    
    print("abc", 3);  

    return 0;
}


/*
run:

The: C Programming.
The: abc.
The: abc.
The: abc.

*/

 



answered Jan 28, 2025 by avibootz

Related questions

2 answers 116 views
1 answer 115 views
1 answer 116 views
1 answer 100 views
1 answer 117 views
2 answers 117 views
2 answers 126 views
...