Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a fixed size for an array in C++

Tags:

c++

Quick and stupid question. How do I declare the size for an array if I'm not allowed to use global variables?

Suppose I have the file Album.h:

class Album {
private:
    Song songs[MAX_SONGS];

    //...

}

where do I put MAX_SONGS = 30? const int MAX_SONGS = 30 is considered a variable right? Please notice that the size should be known to the entire program.

like image 994
Pincopallino Avatar asked Jan 11 '12 21:01

Pincopallino


People also ask

How do you declare a fixed size array?

Fixed arrays have a fixed size which cannot be changed at run-time. These are also known as Static Arrays. An array is declared by including parentheses after the array name or identifier. An integer is placed within the parentheses, defining the number of elements in the array.

Do arrays have fixed size in C?

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

How do you declare an array size?

typeName variableName[size]; This declares an array with the specified size, named variableName, of type typeName. The array is indexed from 0 to size-1. The size (in brackets) must be an integer literal or a constant variable.

Does an array have a fixed size?

Arrays are fixed size. Once we initialize the array with some int value as its size, it can't change.


1 Answers

class Album {
private:
    static const int MAX_SONGS = 100;
    Song songs[MAX_SONGS];

    //...
};

Note that inline initialization of static const variables is only allowed for those whose type is integral. Also note that regardless of initialization, this is still just a declaration and not the definition. You won't generally need the definition, although there are certain cases when you would.

As for the visibility, you can provide a static getter function that would return MAX_SONGS.

public:
static int GetMaxSongs() { return MAX_SONGS; }
like image 73
Armen Tsirunyan Avatar answered Sep 24 '22 21:09

Armen Tsirunyan