Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare a variable inside or outside the main function?

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?

like image 967
Jeffrey Lebowski Avatar asked Dec 06 '22 18:12

Jeffrey Lebowski


2 Answers

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
}
like image 60
sjrowlinson Avatar answered Jan 05 '23 19:01

sjrowlinson


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.

like image 33
SergeyA Avatar answered Jan 05 '23 17:01

SergeyA