首页 > 解决方案 > Use of undeclared identifier 'buffer' and Unused variable 'buffer'

问题描述

im getting a Use of undeclared identifier 'buffer' on memcpy(buffer, &m_Text[index], m_Index - index); and return atof(buffer); and the Unused variable 'buffer' error on char buffer[32] = { 0 }; is there a way of fixing this ? many thanks

double GetNumber()
{
    SkipWhitespaces();

    int index = m_Index;
    while (isdigit(m_Text[m_Index])) m_Index++;
    if (m_Text[m_Index] == '.') m_Index++;
    while (isdigit(m_Text[m_Index])) m_Index++;

    if (m_Index - index == 0)


    char buffer[32] = { 0 };
    memcpy(buffer, &m_Text[index], m_Index - index);

    return atof(buffer);
}

标签: c++compiler-errors

解决方案


让我们添加一些额外的大括号来演示发生了什么

double GetNumber()
{
    SkipWhitespaces();

    int index = m_Index;
    while (isdigit(m_Text[m_Index])) 
    { // added brace
        m_Index++;
    } // added close brace.
    if (m_Text[m_Index] == '.') 
    { // added brace
        m_Index++;
    } // added close brace.
    while (isdigit(m_Text[m_Index]))
    { // added brace
        m_Index++;
    } // added close brace.

    if (m_Index - index == 0)
    { // added brace
        char buffer[32] = { 0 };
    } // added close brace.
    memcpy(buffer, &m_Text[index], m_Index - index);

    return atof(buffer);
}

正如最初写的那样,该if语句没有正文,因此将下一行作为正文。因为char buffer[32] = { 0 }; 是下一行,所以它成为了的一部分,if一旦退出就超出范围,在尝试使用它if时不再存在。memcpy

我强烈建议在学习时始终包括所有大括号。它有助于防止错误。如果你愿意,你可以稍后省略它们,但我总是发现它们比障碍更有帮助。

解决方案

查看源博客的原始代码,我发现

if(m_Index - index == 0) 
    throw ParserException("Number expected but not found!", m_Index);

不是

if (m_Index - index == 0)
 

添加缺少的行(最好与省略的大括号一起),并且char buffer[32] = { 0 };将再次处于正确的范围内。


推荐阅读