1

I'm writing a function and so far I have

size_t CalculusWizard :: _grabDecimal ( std::string::const_iterator it1, std::string::const_iterator it2, std::string & ds )
{
/*
    it1: iterator to the beginning of the decimal string
    it2: iterator to the 1-off-the-end of the range of which the decimal can span
     ds: string to hold the decimal representation

    Reads the decimal in the range [it1, it2) into the string ds
*/
    ds.clear();
    size_t ncp = 0; /* # of characters parsed */
    if (it1 != it2 && *it1 == '-') ds.push_back(*it1++); /* Handle possible minus sign */
    bool foundDot = false;
    while (it1 != it2)
    {
        if (*it1 == '.')
        {
            if (foundDot) break;
            else foundDot = true;
        }
        else if (_digMap.count(*it1) > 0)
        {
         // ...
        }
        else
        {
            break;
        }
        ++it1;
    }
    return ncp;
}

The main question I have concerns the state if (it1 != it2 && *it1 == '-'). I mean for it to be a more compact way of writing

if (it1 != it2)
{
    if (*it == '-') // ...
}

since it's possible that it2 is off the end of the string, and I want to avoid unexpected behavior. But I'm wondering if

(1) the way I wrote it is considered readable

(2) it could cause problems, since it assumes a left-to-right conditional execution of the statements separated by the &&.

Hopefully someone with a deeper knowledge of computer science concepts can explain this to me.

As a bonus, does anyone have a better way of doing what I'm trying to do with this function? All I'm trying to do is grab a decimal representation contained in a string while keeping track of the number of characters that were parsed while getting the decimal. I can't use stod because I lose the information I need.

Steve Jobs
  • 181
  • 5
  • @TartanLlama: No, that is utterly unrelated. Precedence determines how the expression is parsed, not how it's run. And even if we knew that the LHS was evaluated first, we wouldn't be able to answer the question. The key here is that the RHS is not evaluated at all if the LHS is false. – MSalters Mar 10 '15 at 16:00

1 Answers1

0

1) of course... the language wouldn't have && if it wasn't readable to other programmers.

2) no - it won't cause problems. Note that the && operator is a "short circuit" logical operator, and the left-hand-side is evaluated before the right-hand-side, so even code like p && *p == 2 is guaranteed safe when p is a nullptr.

As for how to improve the function... I'd suggest using a std::istringstream to parse the number from the string representation (use std::string::substr if there's a part of a string you want parsed), then you can use tellg on the stream to see how much has been parsed.

A more "C" style alternative is to use strtod - the str_end parameter can capture the position of the first unconverted character.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252