Finding the Variable Name Passed to a Function

get the variable name passed to a function in C

You can't print the address of a variable using function like you've shown. The reason is that a is local variable, which has a different identity than the variable whose value you passed to printAddress.

You also can't get the name, because the name doesn't exist in that context.

However, you could use a macro:

#define printAddress(x)    printf("Address of variable %s is %p\n", #x, &x)

Note that # here is the stringification operator of the preprocessor; it turns a token into a C string literal (effectively just adding quotes around the token).

Full example:

#include <stdio.h>

#define printAddress(x) printf("Address of variable %s is %p\n", #x, &x)

int main(void)
{
int foo;
printAddress(foo);
return 0;
}

Getting the calling variable name of a parameter

You can use a method which is taking an Expression<Func<object>> as parameter:

public void WhatDoesTheAnimalSay_WANTED(Expression<Func<object>> expression)
{
var body = (MemberExpression)expression.Body;
var variableName = body.Member.Name;

var func = expression.Compile();
var variableValue = func();

MessageBox.Show("The "+ variableName + " says: " + variableValue);
}

Using this approach gives the ability to process a variety of variables (static members, instance members, parameters, local variables etc.), also properties are possible.

Call it like:

WhatDoesTheAnimalSay_WANTED(() => dog)
WhatDoesTheAnimalSay_WANTED(() => Cow)
WhatDoesTheAnimalSay_WANTED(() => Cat)
WhatDoesTheAnimalSay_WANTED(() => kiwi)

Constants are not possible, because the compiler will substitute the constant placeholder by its value, given at compile time:

const string constValue = "Constant Value";

WhatDoesTheAnimalSay_WANTED(() => constValue)

would be transformed to

WhatDoesTheAnimalSay_WANTED(() => "Constant Value")

making the expression.Body of type ConstantExpression, which would yield an exception at runtime.

So you have to be careful what you provide as expression to that method.

Additional Remarks

As you can notice from the comments below, the use of lambda expressions to gather variable names seems controversial.

As @CodeCaster pointed out in one of his comments, there is no officially specified need for the compiler to take the same name of a local variable for the captured member in the anonymous wrapping class.

However, I found this in the remarks of Expression<TDelegate>:

The ability to treat expressions as data structures enables APIs to receive user code in a format that can be inspected, transformed, and processed in a custom manner.

For me this is a sign that the expression trees are exactly designed for purposes like that.

Although it is possible that Microsoft changes this behavior for some reason, there does not seem to be a logical need for doing so. Relying on the principle of least astonishment I'd say it is safe to assume that for an expression from ()=> dog whose Body property is of type MemberExpression, that body.Member.Name resolves to dog.

If it is necessary to have other types for Body also, the method has to be worked out a little bit more. And also it is possible that this will not work in certain circumstances anyways.

How to get the original variable name of variable passed to a function

You can't. It's evaluated before being passed to the function. All you can do is pass it as a string.

Get a the name of the variable that was sent as a parameter

No, it's not possible. Variable names only exist in the scope of the method that declare them.

What is passed to the method is not the variable itself, but the value of the variable, so you can't access the name. And even in the case of ref parameters, what is passed is the memory location of the variable, without its name.

original variable name passed to function?

It's not possible. Even pass-by-reference won't help you. You'll have to pass the name as a second argument.

But what you have asked is most assuredly not a good solution to your problem.

Determine original name of variable after its passed to a function

You're right, this is very much impossible in any sane way, since only the value gets passed into the function.

How to find the name of a variable that was passed to a function?

Not really solution, but may be handy (anyway you have echo('foo') in question):

def echo(**kwargs):
for name, value in kwargs.items():
print name, value

foo = 7
echo(foo=foo)

UPDATE: Solution for echo(foo) with inspect

import inspect
import re

def echo(arg):
frame = inspect.currentframe()
try:
context = inspect.getframeinfo(frame.f_back).code_context
caller_lines = ''.join([line.strip() for line in context])
m = re.search(r'echo\s*\((.+?)\)$', caller_lines)
if m:
caller_lines = m.group(1)
print caller_lines, arg
finally:
del frame

foo = 7
bar = 3
baz = 11
echo(foo)
echo(foo + bar)
echo((foo + bar)*baz/(bar+foo))

Output:

foo 7
foo + bar 10
(foo + bar)*baz/(bar+foo) 11

It has the smallest call, but it's sensitive to newlines, e.g.:

echo((foo + bar)*
baz/(bar+foo))

Will print:

baz/(bar+foo)) 11


Related Topics



Leave a reply



Submit