Defining global variable in main()

倖福魔咒の 提交于 2020-01-21 11:47:25

问题


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

回答1:


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.




回答2:


Just define it in global scope

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



回答3:


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


来源:https://stackoverflow.com/questions/13588975/defining-global-variable-in-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!