How to create a function with an optional parameter in C++

3 Answers

0 votes
// Make a parameter optional in C++ by giving it a default value 
// in the function declaration. When the caller doesn’t 
// provide that argument, the default is used.

#include <iostream>
#include <string>

// Optional Parameter With Default Value
void greet(std::string name = "Guest") {
    std::cout << "Hello, " << name << "\n";
}

int main() {
    greet("Vokthar"); 
    greet();        
}



/*
run:

Hello, Vokthar
Hello, Guest

*/

 



answered 3 hours ago by avibootz
0 votes
// Make a parameter optional in C++ by giving it a default value 
// in the function declaration. When the caller doesn’t 
// provide that argument, the default is used.

#include <iostream>
#include <string>

// Optional Parameter With nullptr

void printNumber(int* value = nullptr) {
    if (value != nullptr) {
        std::cout << "Number: " << *value << "\n";
    } else {
        std::cout << "No number provided" << "\n";
    }
}

int main() {
    int x = 10;
    
    printNumber(&x); 
    printNumber();   
}



/*
run:

Number: 10
No number provided

*/

 



answered 3 hours ago by avibootz
0 votes
// Make a parameter optional in C++ by giving it a default value 
// in the function declaration. When the caller doesn’t 
// provide that argument, the default is used.

#include <iostream>
#include <string>
#include <ctime>

// Multiple Optional Parameters

void logMessage(std::string msg, int level = 1, bool timestamp = false) {
    std::cout << "Level " << level << ": " << msg;
    if (timestamp) {
        std::time_t ts = std::time(nullptr);
        std::cout << " [Timestamp: " << ts << "]\n";
    }
    std::cout << "\n";
}

int main() {
    logMessage("Starting");                
    logMessage("Warning", 2);              
    logMessage("Critical", 3, true);       
}



/*
run:

Level 1: Starting
Level 2: Warning
Level 3: Critical [Timestamp: 1777451910]

*/

 



answered 3 hours ago by avibootz
...