【问题标题】:MSVC syntax error with if statement and variable declaration [duplicate]if语句和变量声明的MSVC语法错误[重复]
【发布时间】:2014-08-18 18:56:17
【问题描述】:

我想不出来这个。使用 MSVC 编译器在命令行上编译的纯 C。

Microsoft (R) 32 位 C/C++ 优化编译器版本 15.00.30729.01 用于 80x86
版权所有 (C) 微软公司。保留所有权利。

使用 if (NULL == string) { return NULL; } 块,我收到语法错误。

..\src\drift_charbuffer.c(78) : error C2143: syntax error : missing ';' before 'type'
..\src\drift_charbuffer.c(79) : error C2065: 'index' : undeclared identifier
..\src\drift_charbuffer.c(79) : error C2065: 'index' : undeclared identifier
..\src\drift_charbuffer.c(79) : error C2065: 'index' : undeclared identifier
..\src\drift_charbuffer.c(81) : error C2065: 'index' : undeclared identifier
..\src\drift_charbuffer.c(85) : error C2065: 'index' : undeclared identifier
..\src\drift_charbuffer.c(87) : error C2065: 'index' : undeclared identifier    

但是没有 if 块它编译得很好。我只是看不出这里有什么问题。

char*
drift_charbuffer_tostring(const drift_charbuffer* buffer)
{
    // todo: UTF-8 encoding for characters outside the ASCII-range.
    char* string = drift_alloc(buffer->count + 1);
    if (NULL == string)
    {
        return NULL;
    }

    int index;     // Line: 78
    for (index = 0; index < buffer->count; ++index)
    {
        int value = *drift_charbuffer_get(buffer, index);
        if (value > 127)
            value = '?';

        string[index] = value;
    }
    string[index] = 0;
    return string;
}

【问题讨论】:

  • int index; 移动到块的顶部? (旧 C 可能不允许除块开头以外的变量声明。
  • @chux 是的,就是这样。真的没有想到这一点。它是 Win7 SDK 编译器(我认为是 v110?)。
  • @n.m.既然我们知道问题出在哪里,是的:) 感谢您提供链接 btw
  • 顺便说一句:代码总是可以通过在{ int index; for (index = 0; index &lt; buffer-&gt;count; ++index) { int value = *drift_char buffer_get(buffer, index); if (value &gt; 127) value = '?'; string[index] = value; } string[index] = 0;} 周围添加{} 来创建新的块级别
  • 使用VS2013或C99编译器。

标签: c visual-c++ syntax-error cl


【解决方案1】:

好吧,您的“普通 C”实际上是 C99 或 C99 后的 C。同时,MSVC 编译器仅支持“经典​​的好旧普通 C”AKA C89/90。在经典 C 中,混合声明和声明是非法的。所有声明都必须在块的最顶部完成。

【讨论】:

    猜你喜欢
    • 2015-06-29
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2020-04-16
    • 2010-11-16
    相关资源
    最近更新 更多