Michael Mair <Mi**********@i nvalid.invalid> writes:
David wrote: for example:
int x=10;
char *str="\"x=%d\", x";
if I use
printf(expressi on(str));
then the results is
x=10
even I know it's not easy to return a expression from a function.
can u give me a good idea?
If you tell us what you want to achieve and give us the code
you have up to now or at least your representation of an "expression "
(which is no builtin C datatype).
I think he's done that. His representation of an expression seems to
be a string containing a sequence of arguments to printf, separated by
commas. He wants a function
char *expression (char *expr);
that will return the string that would have been printed by printf().
David, is that about right?
Unfortunately, what you're trying to do is pretty much impossible.
Given a string "x", there's no way in C to get the value of the
variable whose name happens to be x. Variable names appear in source
code, but typically do not appear in the executable program; even if
they do, there's no way to get at them. Roughly speaking, the
compiler decides where x is going to be stored; all references to x in
your program are transformed into references to that memory location,
and the name vanishes.
Now if you explicitly associate the string "x" with the variable,
something like
record_name("x" , &x);
you might be able to do something like what what you describe, but
it's going to be complicated. The above would not be adequate; you'll
also need some way to associate "x" with the type of x, which happens
to be int -- and there's no simple way to represent a type at runtime.
The first thing you should do is decide whether whatever problem
you're trying to solve can be solved in some other way.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.