0

Edit

Now I want to know if it is possible to make ar as a global variable supposing I'm using g++.


My confusion comes from This answer.

Consider the following code:

#include <iostream>
int main() {
    int N;
    std::cin >> N;
    int ar[N] ={0};
    for(int i=0; i<N; i++) {
        std::cout << ar[i] << '\n';
    }
    return 0;
}

This code works perfectly fine. so why saying that we can't do this?

Besides, the real problem I want to solve is how can I make ar global?

#include <iostream>
int N;
int main() {
    std::cin >> N;
    int ar[N] ={0};
    for(int i=0; i<N; i++) {
        std::cout << ar[i] << '\n';
    }
    return 0;
}

The above code only set N to global, but if I want to make ar global, I don't know how to do

Community
  • 1
  • 1
an offer can't refuse
  • 4,245
  • 5
  • 30
  • 50
  • 1
    It's nonstandard but supported by the g++ compiler through an extension – yizzlez Oct 03 '16 at 04:13
  • @awesomeyi What about second question, making it global? – an offer can't refuse Oct 03 '16 at 04:14
  • 1
    @buzhidao *This code works perfectly fine* -- [No it doesn't](http://rextester.com/FDYGC28984). – PaulMcKenzie Oct 03 '16 at 04:17
  • @Cornstalks I know that, but I want to make `ar` global. So that when I using it in another function, I don't need to pass it. – an offer can't refuse Oct 03 '16 at 04:25
  • Oh, sorry, I misunderstood that part. Well in that case you can't create a dynamically sized array. See the duplicate question and answer. You'll either have to dynamically allocate the array or use a container like `std::vector` (which will dynamically allocate it for you, provided you tell it what size to make it). – Cornstalks Oct 03 '16 at 04:32
  • The first part of the code even does not work (at least in g++ 4.6.3). You can not have a variable sized array. – samairtimer Oct 03 '16 at 05:35

0 Answers0