Logo

Programming-Idioms

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

Idiom #108 Determine if variable name is defined

Print the value of variable x, but only if x has been declared in this program.
This makes sense in some languages, not all of them. (Null values are not the point, rather the very existence of the variable.)

puts x if defined?(x)
import std.stdio;
static if (is(typeof(x = x.init)))
    writeln(x);

We test, at compile-time, if an assignExpression with x as lhs would compile, if so we use it.

This technic is sometimes used in template constraints, but rather to test if an operation would be accepted on an argument.

New implementation...
< >
programming-idioms.org