Logo

Programming-Idioms

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

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another Python implementation.

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
if (typeof x !== 'undefined') {
    console.log(x);
}
no strict 'vars';  # the default
print $x;  # compile error

print $x if $main::{x}; # prints $x if it was declared


use strict 'vars';
# or
use v5.11; # or higher

print $x if $main::{x};  # unavoidable compile error

$x = 'foo';

if (isset($x)) {
    echo $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";
}
puts x if defined?(x)
if x then print(x) end
{$if DECLARED(x)}
writeln(x);
{$endif}
import std.stdio;
static if (is(typeof(x = x.init)))
    writeln(x);
implicit none

print *,x
try {
	console.log(x);
} catch (e) {
	if (!e instanceof ReferenceError) {
		throw e;
	}
}
try:
    x
except NameError:
    print("does not exist")
if(@$foo) print($foo);
import java.lang.reflect.Field;
public class Example
{
	public static int x = 1;
	
	public static void printFieldX()
	{
		for(Field field : Example.class.getFields()) {
			if(field.getName().equals("x")) {
				System.out.print(x);
			}
		}
	}
}