I was wondering if there was a more efficient method of handling unary +/- in a recursive expression parser. I have a function that can tell whether or not the operator is unary or not, but when performing the arithmetic I have a less than optimal way of handling it.
The expression itself starts as a string, so when I do come across let's say a unary -, I call a function which replaces the part of the expression which may read, for example, 10*-3, with 10*(0-3)--an expression which the parser can handle easily.
Again, it just doesn't seem all that efficient, so I was wondering if there existed a better way of handling the unary +/- signs.
Not sure how this would work in your program, but the general idea would be that the - sign triggers a flag and is ignored. Then you read the number and if the flag is set return the negative.
I think I understand what you mean, though I'm not sure how to implement it.
And to further explain my method:
The expression from the start is entered in as a string, so I'd have say string s = 10*-3. The parser then loops through operators in the proper order and performs the operation. However, if it comes across a + or -, I call a separate function to test if it's unary. This function checks to the left of the + or - for other operators, and in this case it would fine a *. This means that the - is actually a unary and not an operator. Once it finds this, it calls another function which finds and replaces the unary - in the string with (0-3) and then continues to evaluate the string performing subtraction and multiplication as usual.
It works out fine, it just seems like I'm doing more than I need to.