Should I declare a variable inside or outside the

2020-07-30 03:55发布

In C++, it is advisable to declare global variables inside the main program, or outside it, before everything else? I mean, what is the difference between

#include <iostream>

int variable;

int main()
{    //my program
     return 0;
}

and

#include <iostream>

int main()
{
     int variable;
     //my program
     return 0;
}

In which case should I use which one?

2条回答
我只想做你的唯一
2楼-- · 2020-07-30 04:07

variable in first case is a global variable. It can be accessed from functions other than, and including, main(); is guaranteed to live until program executes; and is set to 0 before first use.

In the second example, variable is a function local variable. It is not initialized to anything unless set by the programmer, can only be accessed within main(), and will be obliterated before main() terminates. That last point is not especially important for main(), but is much more important for other functions.

查看更多
走好不送
3楼-- · 2020-07-30 04:08

In the first case variable is accessible from all other functions in the file (i.e. it has global scope) whereas in the second case it is only accessible from within main. Generally, it's best to keep the amount of global variables you use to an absolute minimum to avoid polluting the variable space (among several other reasons).

Example:

Local to main,

int main(void) {
    int v;
    foo();
    return 0;
}

void foo() {
    v = 5; // compiler error: v not declared in this scope
}

Global,

int v;
int main(void) {
    foo();
    return 0;
}

void foo() {
    v = 5;   // compiles, v declared globally
}
查看更多
登录 后发表回答