Thread: Eval() in C?
View Single Post
  #10   Spotlight this post!  
Unread 09-01-2008, 21:47
Shinigami2057 Shinigami2057 is offline
Slackware Is Your New God (Mentor)
AKA: Harry Bock
FRC #1350 (Rambots)
Team Role: Programmer
 
Join Date: Oct 2006
Rookie Year: 2006
Location: Johnston, RI
Posts: 106
Shinigami2057 is just really niceShinigami2057 is just really niceShinigami2057 is just really niceShinigami2057 is just really niceShinigami2057 is just really nice
Re: Eval() in C?

Quote:
Originally Posted by mluckham View Post
main()
{
char funcname[] = "foo";

...

switch (funcname)
{
case "foo":
foo(a,b);
case "bar":
bar(a,b);
}

...

}
}
Oi... that's going to lead you into a world of trouble.
The C language does not allow for direct comparison of a string, because a string isn't a type, it's a null-terminated array of characters. "foo" is of type const char *, which is an address in your program's memory. funcname is also of type char *, so switch is going to implicitly compare the addresses of the two "strings" and it will never work, because it cannot compare the data at the addresses.

You need to do the following:

Code:
if(strcmp(funcname, "foo") == 0) {
    foo(a, b);
}  else if(strcmp(funcname, "bar")) {
   bar(a, b);
}
Switch only works with strings in PHP and maybe Javascript, as far as I know. You're right though, function pointers are as close to what he's looking for as you can get.
__________________
One of the main causes of the fall of the Roman Empire was that, lacking zero, they had no way to indicate successful termination of their C programs.