【问题标题】:initializing variable in different-different position in windows is giving error在 Windows 中的不同位置初始化变量会出错
【发布时间】:2014-09-23 11:11:37
【问题描述】:

我正在我的代码中初始化简单的 int 变量,但它会产生一些不需要的错误...如果我在某些地方使用整数(或其他数据类型)变量,它会产生错误。我写下我的代码并在整数变量显示错误的地方添加注释。

#include<stdio.h>
#include<Windows.h>

//int i;  ///********* no problem  ************

int main()
{   
    //int i; ///********* no problem  ************
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    //int i; ///********* no problem  ************
    ZeroMemory(&si,sizeof(si));
    //int i;        // error C2143: syntax error : missing ';' before 'type'    
    si.cb=sizeof(si);
    //int i;                 //error C2143: syntax error : missing ';' before 'type' 
    ZeroMemory(&pi,sizeof(pi));

    //int i;        //error C2143: syntax error : missing ';' before 'type'  

    if(CreateProcess("C:\\Windows\\System32\\notepad.exe",NULL,NULL,NULL,FALSE,NORMAL_PRIORITY_CLASS,NULL,NULL,&si,&pi))

    {
        //int i; ///********* no problem  ************
        printf("process created\n pid is=%d   tid is=%d\n",pi.dwProcessId,pi.dwThreadId);

    }
    else
    {   
        //int i; ///********* no problem  ************
        printf("process creation error\n");
    }

    // int i;               // error C2143: syntax error : missing ';' before 'type'  

}

我正在使用 cl.exe 编译器和 Visual Studio 2012。我正在从命令行编译代码

cl process.c 

【问题讨论】:

  • 一个重要提示,您不是在编译 C++ 程序,而是在编译 C 程序。

标签: c++ c windows visual-studio-2012 compiler-errors


【解决方案1】:

Visual Studio 编译器不支持您尝试使用的 C99。

您必须只使用 C90,即将变量声明保持在其包含范围的顶部。

【讨论】:

  • ... 或切换到支持比 25 年前的标准更新的编译器(例如,MinGW 包括 GCC 端口)。
【解决方案2】:

您必须在函数的{ 之后声明所有变量。

这是因为 Visual Studio 支持 C89 并且 C89 禁止混合声明。在 C99 及更高版本中,变量可以在任何地方声明

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2012-01-23
    • 1970-01-01
    • 2018-04-01
    相关资源
    最近更新 更多