main 函数外面和里面有什么区别?

new*_*bie 0 c++ program-entry-point function

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

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

int main(){

}
Run Code Online (Sandbox Code Playgroud)

但是我现在使用的是在 main 函数中,如下所示:

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

那么与它有什么区别呢?

Jon*_*anE 5

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


Vis*_* CS 5

在第一种情况下,变量和指针可以从文件中的所有其他函数访问(即它具有全局作用域),而在第二种情况下,它只能从 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
}
Run Code Online (Sandbox Code Playgroud)

全球的,

#include <iostream>

void fun();

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

void fun() {
  x = 1; // compiles as x declared globally
}
Run Code Online (Sandbox Code Playgroud)