C ++编译器差异(VS2008和g ++)

时间:2009-12-14 12:33:48

标签: 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];

}

此行适用于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

这是一个有效的陈述吗?两个编译器如何对同一个语言有不同的解释

4 个答案:

答案 0 :(得分:14)

这是C99功能:

char arr[a]; // VLA: Variable Length Arrays (C99) but not C++!

GCC支持C99的许多功能,但VC不支持,我认为它不会在不久的将来,因为它们越来越专注于C ++。无论如何,您只需将声明更改为:

  const int a=100; // OK the size is const now!
  char arr[a];

答案 1 :(得分:9)

所有编译器都以微妙的方式实现C ++标准。但是,使用g ++遇到的问题是因为默认情况下它会启用大量的语言扩展。要获得有关这些的警告,您应该始终使用至少-Wall和-pedantic标志进行编译:

g++ -Wall -pedantic myfile.cpp

将提供以下错误/警告:

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

答案 2 :(得分:3)

尝试将int a更改为const int a。 C ++标准规定数组的大小应该是一个常量表达式。常量表达式的定义是(5.19.1):

  

在一些地方,C ++需要   评估为的表达式   积分或枚举常数:as   数组边界(8.3.4,5.3.4),视情况而定   表达式(6.4.2),作为位字段   长度(9.6),作为调查员   初始化器(7.2),作为静态成员   初始化器(9.4.2),并作为整体   或枚举非类型模板   论证(14.3)。常量表达式:   条件表达式一个整数   常量表达只能涉及   文字(2.13),枚举数,常量   变量或静态数据成员   积分或枚举类型   用常量表达式初始化   (8.5),非类型模板参数   积分或枚举类型,和   sizeof表达式。浮动文字   (2.13.3)只有在出现时才会出现   强制转换为整数或枚举类型。   只输入转换为积分或   可以使用枚举类型。在   特别是,除了sizeof   表达式,函数,类对象,   指针或引用不得   使用,分配,增量,   递减,函数调用或逗号   不得使用运营商。

根据此定义,

int a = 100不是常量表达式。

答案 3 :(得分:1)

在microsoft c ++中,创建在堆栈编译时无法确定其大小的数组是无效的。 您必须在堆上创建数组或使用常量来指定数组大小。

char *arr = new char[size];
const int size2 = 100;
char arr2[size2];
相关问题