2

I have a pointer to an int object.

   int x = 10;
   int *ptr;
   ptr = &x;

I want to write a function GetString(int *ptr) which would return me the string ptr. How do I do that in C++?

2 Answers2

2

There isn't a direct way to extract a variable's string name in C++. The language has only rudimentary reflection features, see the type_traits standard library and SO post Why does C++ not have reflection?.

But you can use preprocessor stringification # to hack something similar: define

#define STRINGIFY(x) #x

then the preprocessor substitutes STRINGIFY(ptr) with the string "ptr".

Note: if you want to stringify the result of a macro expansion use two levels of macros.

Pascal Getreuer
  • 2,906
  • 1
  • 5
  • 14
  • I tried this approach, it does work for pointers. The issue is (and that is my fault that the question doesn't reflect the point) that I actually wanted to define a function like this: ```string GetVariableName(int *ptr){ string str = STRINGIFY(ptr); return str;}``` When I do this and then use ```int *alphabeta; GetVariableName(alphabeta);```, it still returns the string ```'ptr'```. It makes sense why the output is this way, but then it renders the STRINGIFY approach moot for me, I think. :( – Diptanil Roy Oct 04 '20 at 14:43
  • Unfortunately, there isn't a way in C++ to accomplish this with a function. The closest you can do is make `GetVariableName` itself the "STRINGIFY" macro, or use an approach like asmmo suggested. – Pascal Getreuer Oct 04 '20 at 19:13
1
#include <iostream>
#include <map>

const std::string& getString(int  *ptr, const std::map<int*, std::string>& mp){
    return mp.find(ptr)->second;

}

int main()
{
    std::map<int* , std::string> mp;

    int x = 10;
    mp.insert({&x, "ptr1"});

    int y = 9;
    mp.insert({&y, "ptr2"});

    std::cout << getString(&y, mp);
}

Demo

asmmo
  • 6,922
  • 1
  • 11
  • 25