Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between File Scope and Global Scope

I am a student and I am confused about global and file scope variables in C and C++. Is there any difference in both perspectives? If yes, please explain in detail.

like image 277
Iqbal Haider Avatar asked Feb 20 '14 05:02

Iqbal Haider


People also ask

What is a file scope?

File Scope: These variables are usually declared outside of all of the functions and blocks, at the top of the program and can be accessed from any portion of the program. These are also called the global scope variables as they can be globally accessed.

What are the differences between file scope and block scope?

Block scope variables are also called local variables. File scope (a.k.a. global scope): Any name declared outside all code blocks or classes has file scope. Such a name is visible anywhere in the file after its declaration. File scope variables are also called global variables.

What is the difference between a local scope and global scope?

A global variable has global scope. A global variable is accessible from anywhere in the code. Local Scope — Local scope contains things defined inside code blocks. A local variable has local scope.


2 Answers

A variable with file scope can be accessed by any function or block within a single file. To declare a file scoped variable, simply declare a variable outside of a block (same as a global variable) but use the static keyword.

static int nValue; // file scoped variable
float fValue; // global variable

int main()
{
    double dValue; // local variable
}

File scoped variables act exactly like global variables, except their use is restricted to the file in which they are declared.

like image 134
Hitesh Vaghani Avatar answered Sep 27 '22 21:09

Hitesh Vaghani


It is perhaps clearer to illustrate file (or more precisely, translation unit)-scope vs global scope when there are actually multiple translation units...

Take 2 files (each being it's own translation unit, since they don't include each other)

other.cpp

float global_var = 1.0f;
static float static_var = 2.0f;

main.cpp

#include <cstdio>

extern float global_var;
//extern float static_var; // compilation error - undefined reference to 'static_var'

int main(int argc, char** argv)
{
    printf("%f\n", global_var);
}

Hence the difference is clear.

like image 32
Rufus Avatar answered Sep 27 '22 21:09

Rufus