Home > Mobile >  how can I allow a method parameter to be null
how can I allow a method parameter to be null

Time:07-19

I'm new to c , and coming from c#;

in c# to achieve my intended goal I would simply do this

public void MyMethod(int? value) {
 if(value is null) {
  // Do something
 } else {
  // Do something else
 }
}

how might I achieve this result, if possible in c ?

CodePudding user response:

You can do this with std::optional.

void MyMethod(const std::optional<int>& option) {
 if(option.has_value()) {
  // Do something with the int option.value()
 } else {
  // Do something else with no value.
 }
}

std::nullopt is what you pass when no value is desired. MyMethod(std::nullopt);

Or if you want to be able to omit the argument entirely and say MyMethod() then you can make the argument default to std::nullopt.

void MyMethod(const std::optional<int>& option = std::nullopt) {

CodePudding user response:

This sounds like a job for overloading:

void f() {
    // do something for no argument
}

void f(int i) {
    // do something with I
}
  •  Tags:  
  • c
  • Related