user490735
user490735

Reputation: 765

Pass data as code

I'm trying to interpret a formula given as input:

y= y argv[1][s] 5;

where argv[1][s] can be + - * for example.
y= y+5;
y= y*5;

I could use a check for specific values, but it's more interesting to find out why this doesn't work.

error C2146: syntax error : missing ';' before identifier 'argv'

I think what happens is that + is passed as '+' so no operation results. Is there a way to unquote this?

Upvotes: 0

Views: 118

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

No, because that's not how C++ works. Your code must make sense at compile-time, so that the compiler can convert it to a fixed set of assembler instructions. Run-time text is not "substituted" in; there is no equivalent of "eval" like in some interpreted languages.

If you want to do this, you'll need to do something like:

switch (argv[1][s])
{
case '+':
    y = y + 5;
    break;
case '-':
    y = y - 5;
    break;
case '*':
    y = y * 5;
    break;
default:
    std::cerr << "Unrecognised operator: \"" << argv[1][s] << "\"" << std::endl;
    break;
}

Upvotes: 8

Related Questions