can we print name of the variable in any programming language?

in every language we only print the value of variable, let me know can we print the name the variable that keep the value?

3/26/2019 9:20:57 AM

Muhammad Idrees

8 Answers

New Answer


You can use reflection in java for getting the variable names. Something like this should work: 😅 (💐 🌸 💮 🏵️ 🥀 🌺 🌻 🌹 🌾🌷) ________________________________ import java.lang.reflect.*; public class MyClass { String name = "Serena"; public static void main(String[] args) { try { Class yv = new MyClass().getClass(); Field[] fields = yv.getDeclaredFields(); for(int i=0; i<fields.length; i++) { System.out.println("Field = " + fields[i].toString()); } } catch(Exception ignored) { } } } (💐 🌸 💮 🏵️ 🥀 🌺 🌻 🌹 🌾🌷) ________________________________


You cannot change the name of variable dynamically, so the most efficient way to print the name of variable is this: int num = 10; System.out.println("Name of my variable is num"); Well, how do you think it will help you?


It's possible to use preprocessor directives to do that in C/C++. Other languages should also provide appropriate debug tools which may/may not include tools to obtain your variable names programmatically. https://stackoverflow.com/questions/3386861/converting-a-variable-name-to-a-string-in-c


In Python you can use locals() or globals() to get names and values as a dict. So you could for example transform that dict into a list of tuples... list(globals().items()) ... and access the name by looking up its value. That may lead to misleading results when several names refer to the same value though. x, y = 5, 5 ... would become... ('x', 5) and ('y', 5)


You can apply such thing in python: - def name_is_my_function(): pass my_func = name_is_my_function print(my_func.__name__)


You can get the key of property in an object in JavaScript by using Object.keys() method: var obj = { name: "Muhammad", age: 25 } var keys = Object.keys(obj) for(let i = 0; i < keys.length; i++) console.log(keys[i]) // output: // name // age It will return an array which contains the variable names you want.


Hi Akmal Your posts seem spammy. Please keep your comments topical to the thread and to the original post.


Reflection can also be used in C# https://stackoverflow.com/questions/2566101/how-to-get-variable-name-using-reflection