【问题标题】:Do compilers put clauses of && statements in the same order in which you write them? [duplicate]编译器是否按照您编写它们的顺序放置 && 语句的子句? [复制]
【发布时间】:2015-03-10 14:48:08
【问题描述】:

我正在写一个函数,到目前为止我有

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;
}

我的主要问题与if (it1 != it2 && *it1 == '-') 状态有关。我的意思是它是一种更紧凑的写作方式

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

因为it2 可能不在字符串的末尾,我想避免意外行为。但我想知道如果

(1) 我写它的方式被认为是可读的

(2) 它可能会导致问题,因为它假定由&& 分隔的语句从左到右有条件地执行。

希望对计算机科学概念有更深入了解的人可以向我解释这一点。

作为奖励,有没有人有更好的方法来做我试图用这个功能做的事情?我要做的就是获取包含在字符串中的十进制表示,同时跟踪在获取小数时解析的字符数。我无法使用stod,因为我丢失了我需要的信息。

【问题讨论】:

  • @TartanLlama:不,这完全不相关。优先级决定了表达式的解析方式,而不是它的运行方式。即使我们知道 LHS 是首先评估的,我们也无法回答这个问题。这里的关键是,如果 LHS 为假,则根本不会评估 RHS。

标签: c++ algorithm compilation logic machine-code


【解决方案1】:

1) 当然...如果其他程序员无法读取该语言,则该语言不会有 &&

2) 不 - 它不会引起问题。请注意,&& 运算符是一个“短路”逻辑运算符,左侧先于右侧求值,因此当 p 是 @ 时,即使像 p && *p == 2 这样的代码也能保证安全987654327@.

至于如何改进功能...我建议使用std::istringstream 来解析字符串表示中的数字(如果您要解析字符串的一部分,请使用std::string::substr),然后您可以在流上使用tellg 来查看已经解析了多少。

更“C”风格的替代方法是使用strtod - str_end 参数可以捕获第一个未转换字符的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多