Do there exist programming languages where a variable can truly know its own name?
- by Job
In PHP and Python one can iterate over the local variables and, if there is only once choice where the value matches, you could say that you know what the variable's name is, but this does not always work. Machine code does not have variable names. C compiles to assembly and does not have any native reflection capabilities, so it would not know it's name. (Edit: per Anton's answer the pre-processor can know the variable's name).
Do there exist programming languages where a variable would know it's name?
It gets tricky if you do something like b = a and b does not become a copy of a but a reference to the same place.
EDIT: Why in the world would you want this? I can think of one example: error checking that can survive automatic refactoring. Consider this C# snippet:
private void CheckEnumStr(string paramName, string paramValue)
{
if (paramName != "pony" && paramName != "horse")
{
string exceptionMessage = String.Format(
"Unexpected value '{0}' of the parameter named '{1}'.",
paramValue,
paramName);
throw new ArgumentException(exceptionMessage);
}
}
...
CheckEnumStr("a", a); // Var 'a' does not know its name - this will not survive naive auto-refactoring
There are other libraries provided by Microsoft and others that allow to check for errors (sorry the names have escaped me). I have seen one library which with the help of closures/lambdas can accomplish error checking that can survive refactoring, but it does not feel idiomatic. This would be one reason why I might want a language where a variable knows its name.