get the variable name passed to a function in C

Viewed 615

I am writing a demo program to print address of the variable. To make the code look cleaner I have created a header file in which the function is declared(ex.pointer.h) and a C file for calling that function(ex. main.c). I want to print the address of the variable with the variable name called in main.c main.c:

#include "pointer.h"

int main(int argc, char *argv[]){
    int var=40;
    printAddress(var);
}

pointer.h

#include<stdio.h>
int *p;
#define getName(var) #var

void printAddress(int a){
    p=&a;
    printf("Address of variable %s is %p\n",getName(a),p);
}

I tried using macros but it printsAddress of variable a is 0x7fff2424407c which is not the expected outputAddress of variable var is 0x7fff2424407c. Can anyone please tell me what changes I should make and please explain.

3 Answers

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;
}

A macro can prepare the name and address of a variable before passing it to the actual function. Do not do this in production code:

#include <stdio.h>


void printAddress(char *name, void *address)
{
    printf("The address of %s is %p.\n", name, address);
}


#define printAddress(x) printAddress(#x, &(x))


int main(void)
{
    int var = 40;
    printAddress(var);
}

I tried using macros but it printsAddress of variable a is 0x7fff2424407c which is not the expected outputAddress of variable var is 0x7fff2424407c.

At the place where you call the getName the variable name is a. There is no way to track back that you have passed a value that has been referenced by variable var before. This is because, as far as the compiler is concerned, you do not pass a "name" of a variable but it value - in this case an integer - which for the purpose of havg the code human readable is names a in the printAddress function body.

Now, the only way to achieve what you want is to get rid of the function and implement the whole thing as a macro.

Alternatively, you could create a template class that would keep the value and a name of the variable as a member variables but that would be an overkill. If you need this for debugging purposes then please consider using debugger such as gdb (or better cgdb) - it would be a much better choice.

Related