SlideShare a Scribd company logo
1 of 6
StaticKeyword
1
Static keyword
We have been using static keyword in our examples. What is the meaning of
static? The word refers to something that is stationary, stopped and not moveable.
What are the types of these variables, declared as static?
How can we make use of them? Static as the word implies are variables which
exist for a certain amount of time, much longer than that by ordinary automatic
variables. Letā€™s consider the example about the lifetime of data variables.
One of the variable types is global variable. Global variables are those that are
defined outside of main. They are written as standalone statements before main
function
int i; the variable ā€˜Iā€™ is a global variable. It is not only accessible in main but also
in all the functions. They can assign some value to ā€˜Iā€™ or obtain the value of ā€˜Iā€™.
Global variables come into existence whenever we execute the program and the
memory is allocated for ā€˜Iā€™. It exists all the time when the program is running. At
the end of the program execution, the memory will be de-allocated and returned to
the operating system. So it has a very long lifetime. We need a value which exists
for the complete execution of the program and is available in all the functions. We
use global variables. It is not a good idea to do that unless it is absolutely
necessary. The major plus point of these variables is that these are accessible from
everywhere in the program. The inconvenience is that these variables are visible in
those functions too which does not need them
The Many Meanings of the C++ ā€œStaticā€ Keyword
In C++, the static keyword has a lot of meanings. Letā€™s go over all of them
Meaning 1: Private Linkage
This one comes from C, and it lets you mark a variable as ā€œfile privateā€.
StaticKeyword
2
Example:
static int i = 42;
void doSomething()
{
cout << i;
}
In this example, static tells the compiler to not make the variable i available from
other sourcefiles. If another file tries to use i, perhaps using the extern keyword, it
would generate a linker error (unresolved external symbol). The same concept
applies to functions whose access you want to limit to the current file.
Uses:
This is very handy for creating ā€œfile privateā€ variables and functions. I recommend
using static for any file-only functions. This way, you can name them whatever
you like without risking a naming collision in the global namespace.
Gotchas:
Unfortunately, you canā€™t declare a class as static. Also, the language makes no
guarantee about the order in which static variables are initialized. In my
experience, static variables in the same file are initialized in a ā€œsaneā€ order, so you
can do things like this
static int i = 42;
static int j = i + 1;
Meaning 2: Function Call Spanning
This one also comes from C, and it lets you give a function-local variable a long
lifespan.
Example:
void foo()
StaticKeyword
3
{
static int callCount = 0;
callCount++;
cout << "foo has been called " << callCount << " times" << endl;
}
Uses:
itā€™s a great way to keep track of how many times a function has been called, so it
works well for generating unique ID numbers (watch out for thread-safety!). Itā€™s
also useful to keep track of whether a function is being called for the first time
ever, like this:
void foo()
{
static boolfirstTime = true;
if(firstTime)
{
// Do something special here
firstTime = false;
}
}
Gotchas:
Static function-local variables are initialized the first time the function is called,
not before. Using these kinds of variables can often make your codenot thread safe
and not re-entrant, so take care before using them. You can put static variables
within scopeblocks (like inside an if or for statement). Iā€™m not totally sure what
StaticKeyword
4
the implications are, and frankly Iā€™ve never felt the need to limit the scopeof a
variable so aggressively.
Meaning 3: Per-Class Data
When you declare a class member as static, it now belongs to the class at large, and
not a particular instance.
Example:
// In the .h file:
class MyClass
{
public:
static int FavoriteNumber;
static void foo();
};
// In the .cpp file (to initialize the static variable):
int MyClass::FavoriteNumber = 42;
void MyClass::foo()
{
// can't access member variables here!
}
Uses:
StaticKeyword
5
Itā€™s very common to store class-level constants this way. You can declare class
functions as static as well, so they would be callable from anyone who has access
to your class, even if they donā€™thave an instance. This is handy for helper
functions. I generally like to make class functions static if they donā€™tneed to
operate on any instance data, typically for private helper functions.
Gotchas:
Static members are initialized very early in your programā€™s execution, before
main() is even called actually. You also have no guarantee about the order in
which they are initialized between classes in different files. Be careful not to
initialize one static class variable from another (possibly not-yet-initialized) static
class variable. Also, you canā€™t access instance data from this within a static class
function (unless someone passes you a this pointer). Lastly, you have to initialize
your static class variables in your implementation (.cpp)file. Otherwise, the
compiler doesnā€™tknow how to allocate them (see the example above).
What is the difference between a static class and a static
member variable or method?
Let's start with the memory first. Whenever a process is loaded in the RAM, we
can say that the memory is roughly divided into three areas (within that process):
Stack, Heap, and Static (which, in .NET, is actually a special area inside Heap
only known as High FrequencyHeap).
The static part holds the ā€œstaticā€ member variables and methods. What exactly is
static? Those methods and variables which don'tneed an instance of a class to be
created are defined as being static. In C# (and Java too), we use the static keyword
to label such members as static. For e.g.
class MyClass
{
public static int a;
public static void DoSomething();
}
StaticKeyword
6
These member variables and methods can be called without creating an instance of
the enclosing class. E.g., we can call the static method DoSomething( ) as:
MyClass.DoSomething();
We don't need to create an instance to use this static method.
Static class declarations
The static keyword in C++ is used to specify that variables will be in
memory till the time the program ends; and initialized only once. Just
like C# and Java, these variables donā€™t need an object to be declared to
use them.
Summary
Static methods in the C# language differ from instance methods in
both the method declarations and in the method call sites. Static
methods apply to a type, not an instance of the type they are
defined on

More Related Content

What's hot

Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keywordtanu_jaswal
Ā 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)harsh kothari
Ā 
Inheritance
InheritanceInheritance
InheritanceJaya Kumari
Ā 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - PolymorphismMudasir Qazi
Ā 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
Ā 
Polymorphism
PolymorphismPolymorphism
PolymorphismKumar
Ā 
Oops concepts
Oops conceptsOops concepts
Oops conceptsKanan Gandhi
Ā 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionPritom Chaki
Ā 
Core Java interview questions-ppt
Core Java interview questions-pptCore Java interview questions-ppt
Core Java interview questions-pptMayank Kumar
Ā 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answersw3asp dotnet
Ā 
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Edureka!
Ā 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in javasureshraj43
Ā 
Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphismumesh patil
Ā 

What's hot (20)

Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
Ā 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
Ā 
Inheritance
InheritanceInheritance
Inheritance
Ā 
C#
C#C#
C#
Ā 
OOP - Polymorphism
OOP - PolymorphismOOP - Polymorphism
OOP - Polymorphism
Ā 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Ā 
Java interface
Java interfaceJava interface
Java interface
Ā 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
Ā 
Abstract method
Abstract methodAbstract method
Abstract method
Ā 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
Ā 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Ā 
Oops concepts
Oops conceptsOops concepts
Oops concepts
Ā 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
Ā 
Core Java interview questions-ppt
Core Java interview questions-pptCore Java interview questions-ppt
Core Java interview questions-ppt
Ā 
C# interview
C# interviewC# interview
C# interview
Ā 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answers
Ā 
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Rust Tutorial | Rust Programming Language Tutorial For Beginners | Rust Train...
Ā 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Ā 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
Ā 
Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphism
Ā 

Viewers also liked

C# feature: case study on facade-type static utility class
C# feature: case study on facade-type static utility classC# feature: case study on facade-type static utility class
C# feature: case study on facade-type static utility classKwork Innovaatiot
Ā 
What is keyword in c programming
What is keyword in c programmingWhat is keyword in c programming
What is keyword in c programmingRumman Ansari
Ā 
Dynamic C#
Dynamic C# Dynamic C#
Dynamic C# Antya Dev
Ā 
Delegates in C#
Delegates in C#Delegates in C#
Delegates in C#SNJ Chaudhary
Ā 
Scope - Static and Dynamic
Scope - Static and DynamicScope - Static and Dynamic
Scope - Static and DynamicSneh Pahilwani
Ā 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little WondersBlackRabbitCoder
Ā 
.NET and C# Introduction
.NET and C# Introduction.NET and C# Introduction
.NET and C# IntroductionSiraj Memon
Ā 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
Ā 

Viewers also liked (8)

C# feature: case study on facade-type static utility class
C# feature: case study on facade-type static utility classC# feature: case study on facade-type static utility class
C# feature: case study on facade-type static utility class
Ā 
What is keyword in c programming
What is keyword in c programmingWhat is keyword in c programming
What is keyword in c programming
Ā 
Dynamic C#
Dynamic C# Dynamic C#
Dynamic C#
Ā 
Delegates in C#
Delegates in C#Delegates in C#
Delegates in C#
Ā 
Scope - Static and Dynamic
Scope - Static and DynamicScope - Static and Dynamic
Scope - Static and Dynamic
Ā 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
Ā 
.NET and C# Introduction
.NET and C# Introduction.NET and C# Introduction
.NET and C# Introduction
Ā 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
Ā 

Similar to Static keyword u.s ass.(2)

Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
Ā 
java tr.docx
java tr.docxjava tr.docx
java tr.docxharishkuna4
Ā 
Static keyword a.z
Static keyword a.zStatic keyword a.z
Static keyword a.zSyed Umair
Ā 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdfKUNALHARCHANDANI1
Ā 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++Reddhi Basu
Ā 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming Appili Vamsi Krishna
Ā 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core ParcticalGaurav Mehta
Ā 
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented PrinciplesSujit Majety
Ā 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer ProgrammingInocentshuja Ahmad
Ā 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questionsnicolbiden
Ā 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptxSajidTk2
Ā 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
Ā 
Storage Class Specifiers
Storage Class SpecifiersStorage Class Specifiers
Storage Class SpecifiersReddhi Basu
Ā 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and AnswersDaisyWatson5
Ā 
Delphi qa
Delphi qaDelphi qa
Delphi qasandy14234
Ā 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questionsGradeup
Ā 
Storage classes
Storage classesStorage classes
Storage classespriyanka jain
Ā 
My c++
My c++My c++
My c++snathick
Ā 

Similar to Static keyword u.s ass.(2) (20)

Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
Ā 
java tr.docx
java tr.docxjava tr.docx
java tr.docx
Ā 
Static keyword a.z
Static keyword a.zStatic keyword a.z
Static keyword a.z
Ā 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdf
Ā 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++
Ā 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
Ā 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
Ā 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
Ā 
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented Principles
Ā 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
Ā 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
Ā 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
Ā 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
Ā 
Storage Class Specifiers
Storage Class SpecifiersStorage Class Specifiers
Storage Class Specifiers
Ā 
Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and Answers
Ā 
Java unit 7
Java unit 7Java unit 7
Java unit 7
Ā 
Delphi qa
Delphi qaDelphi qa
Delphi qa
Ā 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
Ā 
Storage classes
Storage classesStorage classes
Storage classes
Ā 
My c++
My c++My c++
My c++
Ā 

More from Syed Umair

Assignement code
Assignement codeAssignement code
Assignement codeSyed Umair
Ā 
Title page
Title pageTitle page
Title pageSyed Umair
Ā 
Perception
PerceptionPerception
PerceptionSyed Umair
Ā 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word documentSyed Umair
Ā 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)Syed Umair
Ā 
Assignement of programming & problem solving
Assignement of programming & problem solvingAssignement of programming & problem solving
Assignement of programming & problem solvingSyed Umair
Ā 
Assignement of discrete mathematics
Assignement of discrete mathematicsAssignement of discrete mathematics
Assignement of discrete mathematicsSyed Umair
Ā 
Assignment c++12
Assignment c++12Assignment c++12
Assignment c++12Syed Umair
Ā 
Assignement of discrete mathematics
Assignement of discrete mathematicsAssignement of discrete mathematics
Assignement of discrete mathematicsSyed Umair
Ā 
Assignement c++
Assignement c++Assignement c++
Assignement c++Syed Umair
Ā 

More from Syed Umair (20)

Assignement code
Assignement codeAssignement code
Assignement code
Ā 
Tree 4
Tree 4Tree 4
Tree 4
Ā 
Title page
Title pageTitle page
Title page
Ā 
S.k
S.kS.k
S.k
Ā 
Q.a
Q.aQ.a
Q.a
Ā 
Prog
ProgProg
Prog
Ā 
Perception
PerceptionPerception
Perception
Ā 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word document
Ā 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
Ā 
M.b
M.bM.b
M.b
Ā 
C++ 4
C++ 4C++ 4
C++ 4
Ā 
B.g
B.gB.g
B.g
Ā 
Assignement of programming & problem solving
Assignement of programming & problem solvingAssignement of programming & problem solving
Assignement of programming & problem solving
Ā 
Assignement of discrete mathematics
Assignement of discrete mathematicsAssignement of discrete mathematics
Assignement of discrete mathematics
Ā 
A.i
A.iA.i
A.i
Ā 
H m
H mH m
H m
Ā 
Prog
ProgProg
Prog
Ā 
Assignment c++12
Assignment c++12Assignment c++12
Assignment c++12
Ā 
Assignement of discrete mathematics
Assignement of discrete mathematicsAssignement of discrete mathematics
Assignement of discrete mathematics
Ā 
Assignement c++
Assignement c++Assignement c++
Assignement c++
Ā 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
Ā 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
Ā 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
Ā 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
Ā 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
Ā 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
Ā 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
Ā 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
Ā 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
Ā 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
Ā 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
Ā 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
Ā 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
Ā 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
Ā 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
Ā 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
Ā 
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Ā 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
Ā 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
Ā 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
Ā 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Ā 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
Ā 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
Ā 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
Ā 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
Ā 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
Ā 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
Ā 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
Ā 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
Ā 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
Ā 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
Ā 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
Ā 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
Ā 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
Ā 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
Ā 

Static keyword u.s ass.(2)

  • 1. StaticKeyword 1 Static keyword We have been using static keyword in our examples. What is the meaning of static? The word refers to something that is stationary, stopped and not moveable. What are the types of these variables, declared as static? How can we make use of them? Static as the word implies are variables which exist for a certain amount of time, much longer than that by ordinary automatic variables. Letā€™s consider the example about the lifetime of data variables. One of the variable types is global variable. Global variables are those that are defined outside of main. They are written as standalone statements before main function int i; the variable ā€˜Iā€™ is a global variable. It is not only accessible in main but also in all the functions. They can assign some value to ā€˜Iā€™ or obtain the value of ā€˜Iā€™. Global variables come into existence whenever we execute the program and the memory is allocated for ā€˜Iā€™. It exists all the time when the program is running. At the end of the program execution, the memory will be de-allocated and returned to the operating system. So it has a very long lifetime. We need a value which exists for the complete execution of the program and is available in all the functions. We use global variables. It is not a good idea to do that unless it is absolutely necessary. The major plus point of these variables is that these are accessible from everywhere in the program. The inconvenience is that these variables are visible in those functions too which does not need them The Many Meanings of the C++ ā€œStaticā€ Keyword In C++, the static keyword has a lot of meanings. Letā€™s go over all of them Meaning 1: Private Linkage This one comes from C, and it lets you mark a variable as ā€œfile privateā€.
  • 2. StaticKeyword 2 Example: static int i = 42; void doSomething() { cout << i; } In this example, static tells the compiler to not make the variable i available from other sourcefiles. If another file tries to use i, perhaps using the extern keyword, it would generate a linker error (unresolved external symbol). The same concept applies to functions whose access you want to limit to the current file. Uses: This is very handy for creating ā€œfile privateā€ variables and functions. I recommend using static for any file-only functions. This way, you can name them whatever you like without risking a naming collision in the global namespace. Gotchas: Unfortunately, you canā€™t declare a class as static. Also, the language makes no guarantee about the order in which static variables are initialized. In my experience, static variables in the same file are initialized in a ā€œsaneā€ order, so you can do things like this static int i = 42; static int j = i + 1; Meaning 2: Function Call Spanning This one also comes from C, and it lets you give a function-local variable a long lifespan. Example: void foo()
  • 3. StaticKeyword 3 { static int callCount = 0; callCount++; cout << "foo has been called " << callCount << " times" << endl; } Uses: itā€™s a great way to keep track of how many times a function has been called, so it works well for generating unique ID numbers (watch out for thread-safety!). Itā€™s also useful to keep track of whether a function is being called for the first time ever, like this: void foo() { static boolfirstTime = true; if(firstTime) { // Do something special here firstTime = false; } } Gotchas: Static function-local variables are initialized the first time the function is called, not before. Using these kinds of variables can often make your codenot thread safe and not re-entrant, so take care before using them. You can put static variables within scopeblocks (like inside an if or for statement). Iā€™m not totally sure what
  • 4. StaticKeyword 4 the implications are, and frankly Iā€™ve never felt the need to limit the scopeof a variable so aggressively. Meaning 3: Per-Class Data When you declare a class member as static, it now belongs to the class at large, and not a particular instance. Example: // In the .h file: class MyClass { public: static int FavoriteNumber; static void foo(); }; // In the .cpp file (to initialize the static variable): int MyClass::FavoriteNumber = 42; void MyClass::foo() { // can't access member variables here! } Uses:
  • 5. StaticKeyword 5 Itā€™s very common to store class-level constants this way. You can declare class functions as static as well, so they would be callable from anyone who has access to your class, even if they donā€™thave an instance. This is handy for helper functions. I generally like to make class functions static if they donā€™tneed to operate on any instance data, typically for private helper functions. Gotchas: Static members are initialized very early in your programā€™s execution, before main() is even called actually. You also have no guarantee about the order in which they are initialized between classes in different files. Be careful not to initialize one static class variable from another (possibly not-yet-initialized) static class variable. Also, you canā€™t access instance data from this within a static class function (unless someone passes you a this pointer). Lastly, you have to initialize your static class variables in your implementation (.cpp)file. Otherwise, the compiler doesnā€™tknow how to allocate them (see the example above). What is the difference between a static class and a static member variable or method? Let's start with the memory first. Whenever a process is loaded in the RAM, we can say that the memory is roughly divided into three areas (within that process): Stack, Heap, and Static (which, in .NET, is actually a special area inside Heap only known as High FrequencyHeap). The static part holds the ā€œstaticā€ member variables and methods. What exactly is static? Those methods and variables which don'tneed an instance of a class to be created are defined as being static. In C# (and Java too), we use the static keyword to label such members as static. For e.g. class MyClass { public static int a; public static void DoSomething(); }
  • 6. StaticKeyword 6 These member variables and methods can be called without creating an instance of the enclosing class. E.g., we can call the static method DoSomething( ) as: MyClass.DoSomething(); We don't need to create an instance to use this static method. Static class declarations The static keyword in C++ is used to specify that variables will be in memory till the time the program ends; and initialized only once. Just like C# and Java, these variables donā€™t need an object to be declared to use them. Summary Static methods in the C# language differ from instance methods in both the method declarations and in the method call sites. Static methods apply to a type, not an instance of the type they are defined on