a global array in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Malaisary
    New Member
    • Nov 2007
    • 1

    a global array in C++

    I wanted to create an array before int main() function, but compiler didn't allow this. I tried this:
    Code:
    size_t temp_size;
    int varArray[temp_size];
    Another q: why g++ allows declaration of arrays inside int main() without exact value, but Visual C++ 2005 doesn't? It demands some integer values:
    Code:
    int varArray[temp_size]; //g++
    int varArray[200]; //Visual C++ 2005
    How can I make it work in Visual C++ 2005 before calculating temp_size?
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    I wanted to create an array before int main() function, but compiler didn't allow this.
    It is possible to create an array globally. Except you never mentioned what temp_size is, and you can't have an array of unknown size. Also, note that global variables, especially global arrays, are a red flag of bad programming.

    why g++ allows declaration of arrays inside int main() without exact value, but Visual C++ 2005 doesn't?
    Compile with g++, with all warnings and pedantic mode. Watch it fail. g++ has a number of extensions, and I think variable size arrays is one of them. Note that an extension purposely deviates from the C++ standard. You can't have arrays on the stack without specifying their size at compile time. It is your choice to rely on extensions, but if you do so because you don't how to do the equivalent in standard C++, then you are a poor programmer.

    Arrays of unknown compile time size have to be created dynamically on the heap. If you do not know of new/delete and pointers, then you are not advanced enough in your knowledge of C++ to create dynamic arrays.

    Also, since this is C++, take a look at vectors. They are a beginner level topic in C++, and they will allow you to have effectively an array of unknown size.

    Comment

    Working...