Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <iostream>

using namespace std;
#define getName(VariableName) # VariableName
int print(int num)
{
    std::cout<<getName(num)<<": {"<<num<<"}"<<std::endl; 
}
int main()
{
  int  mynum;
    std::cout<<"enter number->"<<std::endl;
    std::cin>>mynum;
    print(mynum);
   
}


What I have tried:

i got output:
enter number->
5
num: {5}
but i need:
mynum: {5}
Posted
Updated 29-Oct-20 7:06am

1 solution

You are calling the macro like this : getName(num), so it can not possibly display mynum. I had a similar problem and I did something like this :
#define printValue( val )   print( val, # val )

int print( int num, const char * name )
{
    std::cout << name << ": {" << num << "}" << std::endl; 
}

int main()
{
    int mynum;
    std::cout << "enter number->" << std::endl;
    std::cin >> mynum;
    printValue( mynum );
}
 
Share this answer
 
Comments
CPallini 29-Oct-20 3:06am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900