0

So I have seen a program from elsewhere and the declaration is outside from the main function. Just like this code:

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

int main(){

}

But what I am using right now is inside the main function like this:

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

So what is the difference from it?

1
  • 1
    outside any function or class scope the variable have global scope. To understand the difference add an function and try using the them.
    – user9400869
    Commented Mar 5, 2020 at 6:45

2 Answers 2

5

In the first case variables and pointers are 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.

I will give you a small example.

Local to 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
}

Global,

#include <iostream>

void fun();

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

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

All variables declared outside of the main function will have global scope and static storage duration. Variables declared inside main will have automatic storage duration (allocated on the stack) if no storage specifier is provided and will only be visible inside main.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.