For C ++ using std :: vector
It makes no sense to use a C array. std :: vector has (almost) the same performance as the C array, and it will:
- grow as needed
- know its size
- make sure you really get access to the correct memory (i.e. it may throw an exception if you go beyond it)
And this is not even a consideration of the general algorithm associated with std :: vector.
Now using c
You can write a little better in at least two ways. First, replacing the definition with a true constant variable:
//
Using a true variable will offer you a slightly safer type and will not pollute the global realm. To minimize dependency, you can even declare variables in the header and define them in the source:
extern const unsigned int MAXPLAYERS ; extern int playerscores[] ; const unsigned int MAXPLAYERS = 4 int playerscores[MAXPLAYERS]; #include "header.h" for(i=0;i<MAXPLAYERS;++i) { .... do something with each player }
Thus, you can resize the array in one source without requiring recompilation of all sources that use it. The downside is that MAXPLAYERS are no longer known at compile time (but, is this really a downside?)
Please note that your second type of array cannot grow dynamically. Sizeof (at least in C ++) is evaluated at compile time. For growing arrays, malloc / realloc / free is the way to switch to C, and std :: vector (or any other common STL container) is the way to switch to C ++.
source share