I'm trying to write a simple function to extract the next number from an expression in a string and my problem is that the reference parameter ioIsValidExpression is not being updated after the function exits. It looks like I am actually referencing the correct variable (and not a temporary) since the addresses of test3 (as it is called before calling getNextNumber(...)) and ioIsValidExpression (its name when inside the function) are the same.
I expect this to be an embarassing mistake somewhere but I'm getting nowhere trying to figure this one out; I've included my int main and int getNextNumber with a comment line where I return a value from the function.
int getNextNumber(std::string& iExpression, int& ioLoopShift, bool& ioIsValidExpression)
{
//spaces are ignored, a minus is a unary minus (so must be seated next to a number (no spaces between '-' and number))
int length = iExpression.size(); //evaluate only once
bool unaryMinusFound = false;
bool numberFound = false;
int oSubExpression = 0;
for(int i =0; i < length; i++)
{
if((int)iExpression[i] == 32)
{
if(!numberFound)
{
if(!unaryMinusFound)
{
continue;
}
else
{
ioIsValidExpression = false;
td::cout << "address of ioIsValidExpression: " << &ioIsValidExpression << ", value: " << ioIsValidExpression << "\n";
return 0;
}
}
else
{
return unaryMinusFound? -1 * oSubExpression: oSubExpression;
}
}
if((int)iExpression[i] == 45 && !unaryMinusFound)
{
unaryMinusFound = true;
continue;
}
if((int)iExpression[i] >= 48 && (int)iExpression[i] <= 57)
{
numberFound = true;
oSubExpression = (int)(iExpression[i]-48) + 10*oSubExpression;
ioLoopShift++;
continue;
}
else
{
//garbage characters
ioIsValidExpression = false;
return 0;
}
}
return unaryMinusFound? -1 * oSubExpression: oSubExpression;
}
int main:
int main(int argc, char* argv[])
{
std::string test = " - 45 & ";
int test2 = 0;
bool test3 = true;
std::cout << getNextNumber(test,test2,test3) << ", address of test3: " << &test3 << ", value: " << test3 << "\n";
return 0;
}
output from running the program:
address of ioIsValidExpression: 0xbf86e58f, value: 0
0, address of test3: 0xbf86e58f, value: 1
The order in which function arguments (and your output statement is a chain of functions) are evaluated is unspecified. Consider how it works correctly upon holding the result of the function in a variable before outputting the whole thing: test
int temp = getNextNumber(test, test2, test3);
std::cout << temp << ", address of test3: " << &test3 << ", value: " << test3 << "\n";
Output:
address of ioIsValidExpression: 0xbfaa85cf, value: 0
0, address of test3: 0xbfaa85cf, value: 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With