函数调用后无法定义变量 [英] Can't define variables after a function call

查看:35
本文介绍了函数调用后无法定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C++ 有丰富的经验,现在我正在尝试用纯 C 做一些事情.但我注意到一个非常奇怪的事实.

I have a great experience of C++, and now I'm trying to do some things in pure C. But I noticed a really strange fact.

以下代码:

#include <stdio.h>

int main()
{
    double a;
    scanf_s("%lf", &a);

    double b;
    b = a + 1;

    printf("%lf", b);

    return 0;
}

在 sourceLair 中编译正常(使用 gcc 编译器,正如我所知),但在 Microsoft Visual Studio(使用 Visual C++)中生成以下错误:

compiles OK in sourceLair (with gcc compiler, as well as I know), but generates following errors in Microsoft Visual Studio (with Visual C++):

1>Task 1.c(8): error C2143: syntax error : missing ';' before 'type'
1>Task 1.c(9): error C2065: b: undeclared identifier
1>Task 1.c(9): warning C4244: =: conversion from 'double' to 'int', possible loss of data
1>Task 1.c(11): error C2065: b: undeclared identifier

我对代码进行了一些试验,并注意到在调用任何函数之前放置一个变量声明是可以的,但是在之后放置一个声明会导致编译错误.

I experimented a bit with the code and noticed that placing a variable declaration before calling any function is OK, but placing a declaration after it results in compilation error.

怎么了?我使用全新安装的 Microsoft Visual Studio 2012 Express,未更改任何设置.

So what's wrong? I use a fresh installation of Microsoft Visual Studio 2012 Express with no settings changed.

推荐答案

假设这是编译为 C,我有一个坏消息要告诉你:Microsoft 的 Visual Studio 自带的编译器不支持 C99,只支持 C89,并且在该语言的修订版,只能在范围的开头声明变量.非声明语句后的声明是错误的.

Assuming that this is being compiled as C, I have bad news for you: Microsoft's compiler that comes with Visual Studio does not support C99, only C89, and in that revision of the language, one can only declare variables at the beginning of a scope. A declaration after a non-declaration statement is an error.

因此,要么重写您的代码,使其符合 C89,要么使用支持 C99 的编译器(例如 GCC,安装 MinGW 后即可使用,或 clang,仅具有与 VS 集成的实验性支持).

So, either rewrite your code so that it conforms to C89, or use a compiler that supports C99 (such as GCC, that can be used after installing MinGW, or clang, which only has experimental support for integration with VS).

这篇关于函数调用后无法定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆