开发者

Why does this compile with the Dev-C++ compiler and not Visual Studio's one?

开发者 https://www.devze.com 2022-12-12 04:02 出处:网络
Why does the following code compile with the Dev-C++ compiler and not with Visual Studio? Any idea? Here is the code:

Why does the following code compile with the Dev-C++ compiler and not with Visual Studio?

Any idea? Here is the code:

#include<stdio.h>
main(){
    int n,i;
    scanf("%d",&n);
    int arr[n];
    for(i= 0 ; i <n ; i++)
    {
         //Do something with the array 
    }
    fflus开发者_C百科h(stdin);
    getchar();
}

Here are the errors:

Errors http://img688.imageshack.us/img688/6618/26863513.jpg


This:

int arr[n];

is invalid because n is not a constant expression. You need to allocate variable sized arrays on the heap using malloc (and then free them when you are done with free).

If you are trying to compile this with a .cpp extension, main must have a return type of int. If you are trying to compile this with a .c extension, then you need to use c-style local variable declaration and declare all of your local variables at the top of the function.


Visual C++ doesn't do stack allocations with that syntax (though I wish it did). You can do stack allocations explicitly with:

int *arr = (int *)_alloca(n*sizeof(*arr));

and no need to free it since it's automatically freed when the scope ends.


This isn’t valid C++ – the Visual C++ compiler does not contain an up-to-date C compiler (rather a C subset of C++) and in particular it doesn’t implement C99 or anything newer. Your code uses features that the Visual C++ compiler doesn’t know (int arr[n]).


To simplify the answers you have gotten:

Your code is C99 and Visual C++ only supports C89. Do yourself a favour and get a better compiler for Windows. The Intel compiler has much better support for C99 than the Microsoft compiler (which has none).


Your program is not a Standard compliant program.

Any standard compliant compiler is required to issue a diagnostic when attempting to compile it.

If Dev-C++ compiled it without a warning, the compiler was invoked in a non compliance mode.

Other than the required diagnostic, a compliant compiler can attempt to compile anyway or just plainly abort compilation.

main()

In C89 this is valid and requires no diagnostic, In C99 this is invalid and requires a diagnostic (valid C99 definitions are int main(void) or int main(int argc, char **argv) or equivalent) ... so if you are using a compliant compiler it is a C89 compiler.

scanf("%d",&n);
int arr[n];

Oops, this is invalid in C89. In C89 you cannot have code intermixed with declarations. A C89 compiler must issue a diagnostic when it sees the declaration of the array.

So ... you are using your compiler in a non-conforming way. There's no way to tell why it compiles or fails to compile.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号