Converting a Variable Name to a String in C++

C - Convert string to variable name

This is simply not possible in C.

Check out this question for more details.
How to return a variable name and assign the value of the variable returned in c

To quote Wichert, 'I suggest that you reconsider the problem you are trying to solve and check if there might not be a better method to approach it. Perhaps using an array, map or hash table might be an alternative approach that works for you.'

Convert any variable to string in C

I think the code below will do your work. I uses the standard sprintf function, which prints data from any type to a string, instead to stdout. Code:

#include <stdio.h>

#define INT_FORMAT "%d"
#define FLOAT_FORMAT "%f"
#define DOUBLE_FORMAT "%lf"
#define LL_FORMAT "%lld"
// ect ...

#define CONVERT_TO_STRING(FORMAT, VARIABLE, LOCATION) \
do { \
sprintf(LOCATION, FORMAT, VARIABLE); \
} while(false)

int main() {
char from_int[30];
char from_float[30];
char from_double[30];
char from_ll[30];

CONVERT_TO_STRING(INT_FORMAT, 34, from_int);
CONVERT_TO_STRING(FLOAT_FORMAT, 34.234, from_float);
CONVERT_TO_STRING(DOUBLE_FORMAT, 3.14159265, from_double);
CONVERT_TO_STRING(LL_FORMAT, 9093042143018LL, from_ll);

puts(from_int);
puts(from_float);
puts(from_double);
puts(from_ll);

return 0;
}

converting a variable name to a string in C++

You can use the preprocessor "stringify" # to do what you want:

#include <stdio.h>

#define PRINTER(name) printer(#name, (name))

void printer(char *name, int value) {
printf("name: %s\tvalue: %d\n", name, value);
}

int main (int argc, char* argv[]) {
int foo = 0;
int bar = 1;

PRINTER(foo);
PRINTER(bar);

return 0;
}

name: foo value: 0
name: bar value: 1

(Sorry for printf, I never got the hang of <iostream>. But this should be enough.)

Programmatic way to get variable name in C?

You could try something like this:

#define DUMP(varname) fprintf(stderr, "%s = %x", #varname, varname);

I used to use this header I wrote, when I was new to C, it might contain some useful ideas. For example this would allow you to print a C value and provide the format specifier in one (as well as some additional information):

#define TRACE(fmt, var) \
(error_at_line(0, 0, __FILE__, __LINE__, "%s : " fmt, #var, var))

If you're using C++, you could use the type of the passed value and output it appropriately. I can provide a much more lucrative example for how to "pretty print" variable values if this is the case.

Convert variable name to string

I managed to solve my problem with this code snippet:

Import the objc runtime

#import <objc/runtime.h>

and you can enumerate the properties with:

- (NSArray *)allProperties
{
unsigned count;
objc_property_t *properties = class_copyPropertyList([self class], &count);

NSMutableArray *rv = [NSMutableArray array];

unsigned i;
for (i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
[rv addObject:name];
}

free(properties);

return rv;
}

Hope it helps someone.

Convert member variable name to a string

As others have said, the name of a variable doesn't actually exist in the generated code once the compiler has finished compiling the code. It may exist in debug symbols or some such, but that's a horrible mess to try to reach into to determine where your variable is located [it may well reside in different places depending on whether the compiler currently is using a register or memory location to store its value, etc, etc].

It is certainly possible to have a macro that produces the matching strin to a name in a parameter.

However, it's probably better to use a different mechanism for configuration type things - a couple of obvious options are:

  1. Using a std::map<std::string, std::string>
  2. Using an array or a vector of std::pair<std::string, std::string>

You could also have a piece of fixed code that understands different configuration settings and their translation to variables. It's not at all a bad solution as long as there aren't a huge number of them.

Or you could build an array like this:

enum config_vals
{
host,
color,
...
max_config
};

struct translation
{
const char *name;
config_vals val;
};

#define TRANS(x) { #x, x }

translation trans[]] = {
TRANS(host),
TRANS(color),
};

class configitems
{
...
std::string value[max_configs];
...
}

...

configitems c;
...
if (c.value[host] == "localhost") ...

Convert string to variable name or variable type

No, this is not possible. This sort of functionality is common in scripting languages like Ruby and Python, but C++ works very differently from those. In C++ we try to do as much of the program's work as we can at compile time. Sometimes we can do things at runtime, and even then good C++ programmers will find a way to do the work as early as compile time.

If you know you're going to create a variable then create it right away:

int count;

What you might not know ahead of time is the variable's value, so you can defer that for runtime:

std::cin >> count;

If you know you're going to need a collection of variables but not precisely how many of them then create a map or a vector:

std::vector<int> counts;

Remember that the name of a variable is nothing but a name — a way for you to refer to the variable later. In C++ it is not possible nor useful to postpone assigning the name of the variable at runtime. All that would do is make your code more complicated and your program slower.



Related Topics



Leave a reply



Submit