sjaustirni
sjaustirni

Reputation: 3237

Defining global variable in main()

I want to define global array (used in other functions) based on input from main(); (concretely array size). The extern keyword didn't help.

#include <iostream>
    using namespace std;

void gen_sieve_primes(void);

int main() {
    int MaxNum;
    cin >> MaxNum;
    int *primes = new int[MaxNum];
    delete[] primes;
    return 0;
}
//functions where variable MaxNum is used

Upvotes: 6

Views: 27152

Answers (3)

Cubic
Cubic

Reputation: 15673

You declare it outside of main:

int maxNum;
int main() {
...
}

Ideally, you don't do this at all. Globals are rarely useful, and hardly ever (or rather: never) needed.

Upvotes: 2

Name
Name

Reputation: 2045

Declare the array outside of the main function's brackets.

#include <iostream>
using namespace std;
void gen_sieve_primes(void);

(Declare the variables here!)

int main() {
     extern int MaxNum;
     cin >> MaxNum;
     int *primes = new int[MaxNum];
     delete[] primes;
     return 0;
}
//functions where variable MaxNum is used

Upvotes: 2

RiaD
RiaD

Reputation: 47619

Just define it in global scope

int MaxNum;
int main(){
    cin >> MaxNum;
}

Upvotes: 5

Related Questions