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

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.)

import std.stdio;
static if (is(typeof(x = x.init)))
    writeln(x);
int x = 42;

void printIfDefined(alias name)()
{
    import std.stdio: writeln;
    static if( __traits(compiles, writeln(mixin(name))))
        writeln(mixin(name));
}

void main(string[] args)
{
    printIfDefined!"x";
    printIfDefined!"Foo.bar";
}
if (typeof x !== 'undefined') {
    console.log(x);
}
if x ~= nil then print(x) end
$x = 'foo';

if (isset($x)) {
    echo $x;
}
{$if DECLARED(x)}
writeln(x);
{$endif}
if defined $x {
	print $x
}
if 'x' in locals():
	print x
puts x if defined?(x)

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

Idiom created by

programming-idioms.org