I'm having no luck trying. Is it possible in C++?

Umm not sure what your saying, some guesses :

const int N = 100;
const float pi = 3.14f;
const string = "what?"
enum{ CONSTANT_1, CONSTANT_2}

struct Foo{
 mutable semiConstant;
}
namespace Math{
 const float DEGTORAD = 0.0174532925f;
}

i mean

int y = 4;
const int x = y;

Oh in that case no. May I ask you what are you trying to achieve?

I'm trying to use the size of a vector, which I have in a counter, to initialize the size of an array.

Ok, why do you need array when you have vectors? Anyways, you can solve that problem with dynamic memory. Here is an example :

std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);

int vecSize = vec.size();

int *Array = new int[vecSize]; //create dynamic array.

for(int i = 0; i < vecSize; ++i)
  cout << Array[i] << endl;


delete Array; //free the memory

Basically, a constant (like "const int some_constant_value = 42;"), whether it is at global scope, namespace scope, or a static data member, has to be assigned to a value that can be resolved at compile-time regardless of when it is initialized.

So, this excludes any variable that is not also a constant. It only allows literal values or other constants, and simple arithmetic operations on literal values and/or other constants. And also #defines, but those are evil.

In the example you gave, since a vector (I'm assuming not a static array) only has a size that can be know at run-time, because it has to be initialized (i.e. created) before it has a known size, and objects only get created at run-time. So, in order to have another array or vector whose size depends on the size of that other vector, it will have to be created at run-time (as firstPerson suggested, using dynamically allocated memory).

If you are talking about the special case where you have a static array (fixed-size, known at compile-time) and you simply want to create another static array of the same size, but you don't want to use a global constant for it, there is a little trick that can be used, but it is not so pretty:

int array1[10]; //say you have this static array, with a "magic number" for its size.

//you can use the sizeof() operator to get the total size in bytes of a _static_ array (only for a static array).
double array2[sizeof(array1) / sizeof(array1[0])]; //it's not pretty, but it works.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.