Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ expected constant expression

#include <iostream>
#include <fstream>
#include <cmath>
#include <math.h>
#include <iomanip>
using std::ifstream;
using namespace std;

int main (void)

{
int count=0;
float sum=0;
float maximum=-1000000;
float sumOfX;
float sumOfY;
int size;
int negativeY=0;
int positiveX=0;
int negativeX=0;
ifstream points; //the points to be imported from file
//points.open( "data.dat");
//points>>size;
//cout<<size<<endl;

size=100;
float x[size][2];
while (count<size) {



points>>(x[count][0]);
//cout<<"x= "<<(x[count][0])<<"  ";//read in x value
points>>(x[count][1]);
//cout<<"y= "<<(x[count][1])<<endl;//read in y value


count++;
}

This program is giving me expected constant expression error on the line where I declare float x[size][2]. Why?

like image 598
n0ob Avatar asked Mar 15 '10 15:03

n0ob


3 Answers

float x[size][2];

That doesn't work because declared arrays can't have runtime sizes. Try a vector:

std::vector< std::array<float, 2> > x(size);

Or use new

// identity<float[2]>::type *px = new float[size][2];
float (*px)[2] = new float[size][2];

// ... use and then delete
delete[] px;

If you don't have C++11 available, you can use boost::array instead of std::array.

If you don't have boost available, make your own array type you can stick into vector

template<typename T, size_t N>
struct array {
  T data[N];
  T &operator[](ptrdiff_t i) { return data[i]; }
  T const &operator[](ptrdiff_t i) const { return data[i]; }
};

For easing the syntax of new, you can use an identity template which effectively is an in-place typedef (also available in boost)

template<typename T> 
struct identity {
  typedef T type;
};

If you want, you can also use a vector of std::pair<float, float>

std::vector< std::pair<float, float> > x(size);
// syntax: x[i].first, x[i].second
like image 166
Johannes Schaub - litb Avatar answered Oct 15 '22 22:10

Johannes Schaub - litb


The array will be allocated at compile time, and since size is not a constant, the compiler cannot accurately determine its value.

like image 39
Justin Ethier Avatar answered Oct 15 '22 21:10

Justin Ethier


You cannot have variable length arrays (as they are called in C99) in C++. You need to use dynamically allocated arrays (if the size varies) or a static integral constant expression for size.

like image 4
dirkgently Avatar answered Oct 15 '22 22:10

dirkgently