Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static class variables the same as extern variables, only with class scope?

Tags:

c++

extern

It seems to me that a static class variable is identical to an extern variable, because you only declare it in the static int x / extern int x statement, and actually define it elsewhere (usually in a .cpp file)

static class variable

// .h file
class Foo
{
    static int x ;
} ;

// .cpp file
int MyClass::x = 0 ;

Extern variables:

// .h file
extern int y;

// .cpp file
int y = 1;

In both cases the variable is declared once somewhere, and defined in a file that will not be included more than once in the compilation (else linker error)

like image 642
bobobobo Avatar asked Oct 27 '11 14:10

bobobobo


People also ask

Can a static variable be extern?

3.1. Static variables in C have the following two properties: They cannot be accessed from any other file. Thus, prefixes “ extern ” and “ static ” cannot be used in the same declaration. They maintain their value throughout the execution of the program independently of the scope in which they are defined.

What is the difference between extern and static?

static means a variable will be globally known only in this file. extern means a global variable defined in another file will also be known in this file, and is also used for accessing functions defined in other files.

Are class variables and static variables the same?

Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword 'static'. Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.

Do static variables have a scope?

In terms of scope and extent, static variables have extent the entire run of the program, but may have more limited scope. A basic distinction is between a static global variable, which has global scope and thus is in context throughout the program, and a static local variable, which has local scope.


2 Answers

Yes, both have static storage duration and external linkage; they have essentially the same run-time properties, only differing in (compile-time) visiblity.

like image 192
Mike Seymour Avatar answered Oct 22 '22 14:10

Mike Seymour


More or less. Both have external linkage, and static lifetimes. Both will be initialized on program start-up, and destructed on exit.

like image 23
James Kanze Avatar answered Oct 22 '22 14:10

James Kanze