tom*_*h13 6 c++ compiler-errors
我尝试在Linux和VS 2008中编译以下代码:
#include <iostream> // this line has a ".h" string attached to the iostream string in the linux version of the code
using namespace std; // this line is commented in the linux version of the code
void main()
{
int a=100;
char arr[a];
arr[0]='a';
cout<<"array is:"<<arr[0];
}
Run Code Online (Sandbox Code Playgroud)
此行在g ++版本中有效,但在Visual Studio中不起作用.它会引发以下错误:
1>c:\users\bibin\documents\visual studio 2008\projects\add\add\hello.cpp(7) : error C2057: expected constant expression
1>c:\users\bibin\documents\visual studio 2008\projects\add\add\hello.cpp(7) : error C2466: cannot allocate an array of constant size 0
1>c:\users\bibin\documents\visual studio 2008\projects\add\add\hello.cpp(7) : error C2133: 'arr' : unknown size
Run Code Online (Sandbox Code Playgroud)
这是一个有效的陈述吗?两个编译器如何对同一语言有不同的解释
Ara*_*raK 14
这是C99功能:
char arr[a]; // VLA: Variable Length Arrays (C99) but not C++!
Run Code Online (Sandbox Code Playgroud)
GCC支持C99的许多功能,但VC没有,我认为它不会在不久的将来,因为他们越来越专注于C++.无论如何,您只需将声明更改为:
const int a=100; // OK the size is const now!
char arr[a];
Run Code Online (Sandbox Code Playgroud)
小智 9
所有编译器都以微妙的方式实现C++标准.但是,使用g ++遇到的问题是因为默认情况下它会启用大量的语言扩展.要获得有关这些的警告,您应该 始终使用至少-Wall和-pedantic标志进行编译:
g++ -Wall -pedantic myfile.cpp
Run Code Online (Sandbox Code Playgroud)
这会产生以下错误/警告:
myfile.cpp:1:119: error: iostream.h: No such file or directory
myfile.cpp:2: error: '::main' must return 'int'
myfile.cpp: In function 'int main()':
myfile.cpp:6: warning: ISO C++ forbids variable length array 'arr'
myfile.cpp:9: error: 'cout' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3341 次 |
最近记录: |