主要功能外部和内部有什么区别?

what is the difference between outside the main function and inside?

所以我在别处看到一个程序,声明在主函数之外。 就像这段代码:

#include<iostream>
using namespace std;
int num1, num2;
int *ptr1 = &num1, *ptr2 = &num2;
char operation, answer;
char *ptrop = &operation;

int main(){

}

但是我现在使用的是在 main 函数里面,像这样:

#include<iostream>
using namespace std;
int main(){
    int num1, num2;
    int *ptr1 = &num1, *ptr2 = &num2;
    char operation, answer;
    char *ptrop = &operation;

那么它有什么区别呢?

main 函数之外声明的所有变量都将具有全局范围和静态存储持续时间。如果未提供存储说明符,则在 main 内声明的变量将具有自动存储持续时间(在堆栈上分配),并且仅在 main.

内可见

在第一种情况下,变量和指针可以从文件中的所有其他函数访问(即它具有全局范围),而在第二种情况下,它只能从 main 中访问。

我给大家举个小例子

本地到主,

#include <iostream>

void fun();

int main(void) {
  int x;
  fun();
  return 0;
}

void fun() {
  x = 1; // compiler error: x not declared in this scope
}

全球,

#include <iostream>

void fun();

int x;
int main(void) {
  fun();
  return 0;
}

void fun() {
  x = 1; // compiles as x declared globally
}