Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #225 Declare and use an optional argument

Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise

function f( x )
	if x then
		print("Present", x)
	else
		print("Not present")
	end
end
#include <optional>
#include <iostream>
void f(std::optional<int> x = {}) {
  if (x) {
    std::cout << "Present" << x.value();
  } else {
    std::cout << "Not present";
  }
}
#include <optional>
#include <iostream>
void f(std::optional<int> x = {}) {
  std::cout << (x ? "Present" + std::to_string(x.value()) : "Not Present");
}
subroutine f(x)
  integer, optional :: x
  if (present(x)) then
    print *,"Present", x
  else
    print *,"Not present"
  end if
end subroutine f
   
function f(?int $x = null) {
    echo $x ? 'Present' . $x : 'Not present';
}
procedure f; overload;
begin
  writeln('not present');
end;

procedure f(x: integer); overload;
begin
  writeln('present');
end;
def f(x=None):
    if x is None:
        print("Not present")
    else:
        print("Present", x)
def f( x=nil )
  puts x ? "present" : "not present"
end

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

tkoenig