我应该在主函数内部还是外部声明一个变量? [英] Should I declare a variable inside or outside the main function?

查看:195
本文介绍了我应该在主函数内部还是外部声明一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,建议在其他所有内容之前在主程序内部或外部声明全局变量?我的意思是,两者之间有什么区别

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;
}

#include <iostream>

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

在哪种情况下我应该使用哪个?

In which case should I use which one?

推荐答案

在第一种情况下,可以从文件中的所有其他函数访问variable(即,它具有全局范围),而在第二种情况下,只能从目录中访问variablemain之内.通常,最好将您使用的全局变量的数量保持为绝对最小值,以避免污染变量空间(还有其他一些原因).

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).

示例:

本地到主要

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

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

全局

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

void foo() {
    v = 5;   // compiles, v declared globally
}

这篇关于我应该在主函数内部还是外部声明一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆